Skip to content

Debounced function calls should be cleaned up on unmount #1322

@domarmstrong

Description

@domarmstrong
  • downshift version: master

Problem description:

I'm getting some intermittent test failures from a status message being added to the document by a previous test due to a debounce not being cleaned up.

Suggested solution:

updateA11yStatus(

function useA11yMessageSetter(
  getA11yMessage,
  dependencyArray,
  {isInitialMount, highlightedIndex, items, environment, ...rest},
) {
  // Sets a11y status message on changes in state.
  useEffect(() => {
    if (isInitialMount || isReactNative) {
      return
    }

    updateA11yStatus(
      () =>
        getA11yMessage({
          highlightedIndex,
          highlightedItem: items[highlightedIndex],
          resultCount: items.length,
          ...rest,
        }),
      environment.document,
    )
    
    // cancel the debounced function in cleanup
    return () => updateA11yStatus.cancel()
    
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, dependencyArray)
}

This isn't a perfect solution as when there are multiple instances, one unmounting could affect calls made from another instance. You could either track the number of instances, or make the callbacks specific to each instance though.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions