šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

How to add debounce to useEffect() in React

In the case where we want to build a React search box, or autocomplete text input, a debounce function comes very handy as we don't want to have the API called for each keystroke of the user.

So, instead of having something like this:

useEffect(() => {
    doApiCall(query)
}, [query]);

We want to have something like this:

useEffect(() => {
    (doApiCall(query)
}, [waitForTheTypingToStop(query)]);

Below is the full code of one possbile solution:

function debounce(callback, time) {
    let interval;
    return () => {
        clearTimeout(interval)
        interval = setTimeout(() => {
                interval = null
                callback(arguments)
            }, time)
    }
}

const App = ({wait = 1000}) => {
    const [query, setQuery] = useState("abc");
    const ref = useRef();

    const onChange = () => console.log("query = ", query)

    useEffect(() => {
        ref.current = onChange
    }, [onChange]);

    const doCallbackWithDebounce = useMemo(() => {
        const callback = () => ref.current()
        return debounce(callback, wait);
    }, []);

    return (<div>
        <p>Input debounced for {wait} ms:</p>
        <input
            value={query}
            onChange={(e) => {
                doCallbackWithDebounce();
                setQuery(e.target.value);
            }} />
    </div>);
}

It will debounce the action used in useEffect() for a given number of milliseconds thus limiting the number of expensive operations, such as API calls:
screenshot of search debounced component in React

You can checkout the working example here and the full code on my Github.

By the way, if you are interested, I've also written this article on why it's great to use React Strict Mode to double-check for errors when working with useEffect().

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *