Debounce Hook for Search Box Auto-Completion

Dec 6, 2022by, Mishab Ameer

Technology

We frequently need to develop a search function on a website. Auto-completion is a fantastic tool for improving a user’s search experience.

We know that we can use React’s useEffect hook to initiate a fetch API request whenever the search box’s input changes. The API call, on the other hand, will be made whenever the user types a single character. When the data sets to be searched grow larger, or if users have a sluggish internet connection, this may cause performance concerns. We could develop a debounce function for our auto-complete feature to avoid visiting the API endpoints so frequently.

The debounce function for querying is a means to slow down the querying process by making the request only after the user has stopped typing for a given amount of time. The goal is to use this hook to wrap the state we want to keep track of, and then only setState once some time has passed. After that, we’ll use the returned state from the hook in the useEffect hook that calls the API to make the API request.

Debounce hook in application:

import { useState, useEffect } from 'react';
const useDebounce = (value, timeout = 500) => {
        const [state, setState] = useState(value);
        useEffect(() => {
                      const handler = setTimeout(() => setState(value), timeout);
                      return () => clearTimeout(handler);
         }, [value, timeout]);
         return state;

}
export default useDebounce;

The idea is to start with the value passed in (the query text) and listen for a change in value. This function’s useEffect hook will be called if the value changes, and it will attempt to setState when a given amount of time has passed (the setTimeout that we defined). If the user continues to type, the useEffect hook will be triggered once more, and the cleaning of useEffect (the return statement) will be executed first to clear the previous timeout handler. As a result, the state will only be restored once the user has finished typing.
useEffect hook in fetch call:

 import React, { useState, useEffect } from "react";

  const [query, setQuery] = useState("");

  const debouncedQuery = useDebounce(query, 500);

  const listAllResults = async () => {

      try {

     const response = await `https://someapi.com/search?q=${debouncedQuery}`;

        if (response) {

         console.log(response.JSON())

        }

      } catch ({ error }) {

        console.log("Oops an error occurred", error);

      } 

    }

useEffect(() => {

    fetchResults();

  }, [debouncedQuery]);


React 18 has included a new hook called useDeferredValue. It accepts a value and postpones updating it. The advantage of using this hook is that we don’t have to set a hardcoded fixed time for the debounce; instead, it will return as soon as the other work is completed.

const deferredValue = useDeferredValue(value);

useDeferredValue takes a value and returns a new copy of it that will be deferred to more important modifications. If the current render is the result of an urgent update, such as user input, React will return the previous value before rendering the new value once the urgent render is complete.

This hook is comparable to user-space hooks that defer updates using debouncing or throttling. The advantages of using useDeferredValue are that React will start working on the update as soon as other work is completed (rather than waiting an arbitrary length of time), and delayed values, like startTransition, can stop without causing an unexpected fallback for existing content.

So using the debounce hook to implement the search function in your react application can optimize the application by minimizing the API call made when each value in search is typed. This function helps us to set an interval so that API calls take place only after the completion of our search keyword. If you have any projects regarding the above, contact us.

Disclaimer: The opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Dexlock.

  • Share Facebook
  • Share Twitter
  • Share Linkedin