How to create a dynamic search using Rxjs debounce custom hook in react

Antonio Mesquita
2 min readOct 2, 2020

It’s very common to face the problem you want to create a dynamic search inside your react app.

The first solution that comes to mind is probably to store the input in a state and update it while the user texts. And every time the user types we send a new request to the backend (as you don’t want to create a button to submit that input only when the user finishes).

Maybe we just need to set up a delay every time the user types and when he has already typed the full string he wants to search we will manage it content as we want. eg.: dispatching an action, filtering a list or anything you want.

That delay will reset every time the person types a character, of course. And as soon as the debounce reaches it’s delay time, we will manage the data. That way we minimize the number of requests to our backend and increase the user experience with a clean and fluid dynamic search.

Less talk and let’s code. All you’re going to need is Rxjs and React (of course).

yarn add rxjs

First we create a state with an initial value from the hook second parameter.

And another state with an initial callback function to Rxjs Subject class, that is simply an special type of observable which shares a single execution path among observers.

We create a pipe to our values subject. Pipeable operators are functions, so they could be used like ordinary functions.

That pipe triggers a debounceTime function from Rxjs that is responsible to discard emitted values that took less than the time received from the useDebounce hook first parameter.

Then we can simply set the new state value with the subscribe method.

And of course in the useEffect we monitor the changes from our two variables: time and values.

It’s important to assign that operation to a variable to safely unsubscribe our observable when our component is unmounted.

Finally we return an array, exactly working as an useState hook from react. The first element is the current value storage with the debounce hook and the second one is the function that we will call from our component. As a useState it will receive a string value to our debounce hook to set the hole operation queue.

And it’s all done :P

Hope you enjoy! Leave a comment below so we can discuss more about it :)

--

--

Antonio Mesquita

Technology lover and always looking for the best frameworks to build incredible things.