Create a Debounce Hook for Search Box Auto-Completion

Photo by Arnold Francisca on Unsplash

It is common that we have to implement a search function for the items on a website. Auto-completion is a great feature to improve the searching experience of users.

We know that we can utilize useEffect hook from React to make the fetch API call whenever the input to our search box changes. However, the API call will be fired whenever the user types a single character. This might cause some performance issues when the data sets to be searched are growing larger, or if users are having slow internet connection. In order to prevent hitting the API endpoints such frequent, we could implement a debounce function for our auto-complete feature.

Debounce function for making query is a way to slow down the process of querying and will make the request only after a certain amount of time when the user stops typing. The idea is to wrap the state that we want to keep track of with this hook, and only setState after waiting for some time. After that, in the useEffect hook that calls the API, we will use this returned state from the hook to make the API call.

This is what the hook looks like:

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 use the passed in value (the query text) as the initial state, and listen for the change of value. Whenever the value changes, useEffect hook of this function will get triggered and try to setState after a certain time (the setTimeout that we defined). However, if the user keeps on typing, the useEffect hook will get triggered again and the cleaning of useEffect (the return statement) will run first to clear the previous timeout handler. This is why the state will only return after the user stopped typing.

This is how we can use this hook in the fetch call useEffect hook (I only show the minimal amount of code to demonstrate):

import React, { useState, useEffect } from 'react';
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 500);
useEffect(() => {
const fetchResults = () => {
fetch(`https://api.someapi.com/search?q=${debouncedQuery}`)
.then(result => result.json())
.then(data => {
// parsed the data and set the options
})
.catch(err => console.error(err))
}
fetchResults();
}, [debouncedQuery]);

Click on the link to check out the live demo: Live Demo

Recently, a new hook — useDeferredValuewas introduced by React 18. It takes in a value and defers the update of it. The benefit of this hook is that we do not set a hardcoded fixed time for the debounce, it will return as soon as the other work finishes.

const deferredValue = useDeferredValue(value);

You can check out this hook in the official React documentation: link.

Do follow me if you would like to see more web development or software engineering-related content. Cheers!


Create a Debounce Hook for Search Box Auto-Completion was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Dylan Oh

Photo by Arnold Francisca on Unsplash

It is common that we have to implement a search function for the items on a website. Auto-completion is a great feature to improve the searching experience of users.

We know that we can utilize useEffect hook from React to make the fetch API call whenever the input to our search box changes. However, the API call will be fired whenever the user types a single character. This might cause some performance issues when the data sets to be searched are growing larger, or if users are having slow internet connection. In order to prevent hitting the API endpoints such frequent, we could implement a debounce function for our auto-complete feature.

Debounce function for making query is a way to slow down the process of querying and will make the request only after a certain amount of time when the user stops typing. The idea is to wrap the state that we want to keep track of with this hook, and only setState after waiting for some time. After that, in the useEffect hook that calls the API, we will use this returned state from the hook to make the API call.

This is what the hook looks like:

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 use the passed in value (the query text) as the initial state, and listen for the change of value. Whenever the value changes, useEffect hook of this function will get triggered and try to setState after a certain time (the setTimeout that we defined). However, if the user keeps on typing, the useEffect hook will get triggered again and the cleaning of useEffect (the return statement) will run first to clear the previous timeout handler. This is why the state will only return after the user stopped typing.

This is how we can use this hook in the fetch call useEffect hook (I only show the minimal amount of code to demonstrate):

import React, { useState, useEffect } from 'react';
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 500);
useEffect(() => {
const fetchResults = () => {
fetch(`https://api.someapi.com/search?q=${debouncedQuery}`)
.then(result => result.json())
.then(data => {
// parsed the data and set the options
})
.catch(err => console.error(err))
}
fetchResults();
}, [debouncedQuery]);

Click on the link to check out the live demo: Live Demo

Recently, a new hook — useDeferredValuewas introduced by React 18. It takes in a value and defers the update of it. The benefit of this hook is that we do not set a hardcoded fixed time for the debounce, it will return as soon as the other work finishes.

const deferredValue = useDeferredValue(value);

You can check out this hook in the official React documentation: link.

Do follow me if you would like to see more web development or software engineering-related content. Cheers!


Create a Debounce Hook for Search Box Auto-Completion was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Dylan Oh


Print Share Comment Cite Upload Translate Updates
APA

Dylan Oh | Sciencx (2022-05-31T12:18:32+00:00) Create a Debounce Hook for Search Box Auto-Completion. Retrieved from https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/

MLA
" » Create a Debounce Hook for Search Box Auto-Completion." Dylan Oh | Sciencx - Tuesday May 31, 2022, https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/
HARVARD
Dylan Oh | Sciencx Tuesday May 31, 2022 » Create a Debounce Hook for Search Box Auto-Completion., viewed ,<https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/>
VANCOUVER
Dylan Oh | Sciencx - » Create a Debounce Hook for Search Box Auto-Completion. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/
CHICAGO
" » Create a Debounce Hook for Search Box Auto-Completion." Dylan Oh | Sciencx - Accessed . https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/
IEEE
" » Create a Debounce Hook for Search Box Auto-Completion." Dylan Oh | Sciencx [Online]. Available: https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/. [Accessed: ]
rf:citation
» Create a Debounce Hook for Search Box Auto-Completion | Dylan Oh | Sciencx | https://www.scien.cx/2022/05/31/create-a-debounce-hook-for-search-box-auto-completion-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.