useEffect.dev
← Back to lessons

Lesson 9. Debouncing a user input 3. A custom hook for debouncing

The custom hook (let’s call it useDebouncedState) should work like useState, returning the debounced value and a setter, but note that it should also return the value before it is debounced. Indeed, in our example, while we want to use the debounced value to perform the search, we still want to use the not-debounced value to display in the input.

So we expect to call our hook this way:

const [search, debouncedSearch, setSearch] = useDebouncedState('')

Here is a proposal for implementation. It is an extract of the previous example's debouncing logic, with some variables renamed to be more generic. We accept two parameters: the state's initial value and an optional delay for the debounce (300 milliseconds by default).

Result

We could introduce other options in this hook. Some implementations you can find on the Internet offer the ability to specify whether or not the debounced value should be updated at initialization or not. Or we could also consider whether or not the API promise is resolved or not before updating the debounced value. I let you refine this hook according to your needs.