Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useDebouncedCallback doesn't consider its dependencies #420

Open
fabn opened this issue Nov 29, 2023 · 3 comments
Open

useDebouncedCallback doesn't consider its dependencies #420

fabn opened this issue Nov 29, 2023 · 3 comments
Labels
bug Something isn't working good first issue Good for newcomers help wanted Extra attention is needed

Comments

@fabn
Copy link

fabn commented Nov 29, 2023

Describe the bug

This is the same issue reported in #386 for useDebouncedCallback, I don't know why that issue has been closed. I'd expect that any dependency given as args will invalidate the callback but that's not the case because deps are not given to the useEffect call here. As result the callback sees the values as one step behind.

To Reproduce

Here's a codesandbox to reproduce the issue https://codesandbox.io/p/sandbox/pedantic-grass-f9f6qw

Expected behavior

When I click on useDebouncedCallback button I should see same values as other buttons in console, but I see the old counter value.

Screenshots

image

@antonioru
Copy link
Owner

Hey @fabn thanks for opening this issue, I really appreciate it
Yeah this is definitely a bug and should be a one-liner, please feel free to open a PR yourself if you feel like it

@antonioru antonioru added bug Something isn't working help wanted Extra attention is needed good first issue Good for newcomers labels Nov 30, 2023
@fabn
Copy link
Author

fabn commented Dec 3, 2023

I tried various changes including this one but it seems to not fix the problem.

const useDebouncedCallback = <TCallback extends GenericFunction>
  (fn: TCallback, dependencies?: DependencyList, wait: number = 600, options: DebounceOptions = defaultOptions) => {
  const debounced = useRef(debounce<TCallback>(fn, wait, options))
  const actualDependencies = dependencies ?? []

  useEffect(() => {
    debounced.current = debounce(fn, wait, options)
  }, [fn, wait, options, ...actualDependencies])

  useWillUnmount(() => {
    debounced.current?.cancel()
  })

  return useCallback(debounced.current, actualDependencies)
}

baradoner pushed a commit to baradoner/beautiful-react-hooks that referenced this issue Jul 17, 2024
…ntonioru#420)

🐛 Fix bug in useDebouncedCallback where dependencies were not considered (antonioru#420)
@baradoner
Copy link

Hi @fabn, probably too late, but I submitted a PR that fixes the problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

3 participants