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

[BUG] useDebounceCallback doesn't seem to memoize the callback function #656

Open
marcebdev opened this issue Nov 13, 2024 · 1 comment
Open
Labels
bug Something isn't working

Comments

@marcebdev
Copy link

marcebdev commented Nov 13, 2024

Describe the bug

Debounce is called multiple times if you use a non-memoized function, like an inline arrow function or something you'd typically put into a useCallback (so not passing a setState or similar directly).

Using a custom arrow function like you'd use in useCallback or something similar is not uncommon nor unresonable. Many other libraries show better examples (than passing a useState directly) and use something like this as an example e.g. https://mantine.dev/hooks/use-debounced-callback/

So the issues are many fold:

  1. a stronger example is needed, as we can see useState is basically cheating
  2. improve tests as critical test cases are missed
  3. fix bug (it is not a useCallback variant hook without this fix)

To Reproduce

const Test = () => {
  const [value, setValue] = useState<string>('')
  const [, setDebouncedValue] = useState('')

  const debounce = useDebounceCallback((val: string) => {
    console.log('debounced', val)
    if (value) setDebouncedValue(val)
  }, 1500)

  return (
    <input
      value={value}
      onChange={({ target: { value } }) => {
        setValue(value)
        debounce(value)
      }}
    />
  )
}

Expected behavior

debounced functions should be called once

Right now that console will print the following if "123" is typed

debounced 1
debounced 12
debounced 123

Additional context

No response

@marcebdev marcebdev added the bug Something isn't working label Nov 13, 2024
@marcebdev
Copy link
Author

marcebdev commented Nov 20, 2024

I don't mean to be bitter or rude and can def appreciate the contributions to this library, but given such a critical/misdocumented issue with this hook and seeing other debounce hook related issues I think I'll step away from using this library for now.

FWIW this library has one of my fav set of functions but if they don't work reliably, it's hard to confidently rely on them

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant