Skip to content

[BUG] useDebounceCallback does not debounce when the options object is unstable #703

@lolmaus

Description

@lolmaus

Describe the bug

It is fine that useDebounceCallback requires stabilizing the callback function with useMemo. There may be a case where the callback function changes, which requires resetting the debouncing.

But there is no sense in resetting debouncing on the change of the options object, because there is no practical case where the options object may be updated dynamically.

To Reproduce

In a React component:

  const search = useCallback(() => {/*...*/}, []);
  const searchDebounced = useDebounceCallback(search, 500, { leading: true });

This will never debounce because {leading: true} is a literal that is recreated with a unique instance on every rerender of the component.

Expected behavior

This should just work.

But the current implementation forces the developer to memoize the options object like this:

  const search = useCallback(() => {/*...*/}, []);
  const debounceOpts = useMemo(() => ({ leading: true }), []);
  const searchDebounced = useDebounceCallback(search, 500, debounceOpts);

This is ridiculous, annoying and causes a lot of frustration to developers. It took me two hours of hair pulling and abusing AIs to realize what the cause of the problem is.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions