Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created September 10, 2022 06:12
Show Gist options
  • Save ahamed/75b36b7f55b1b688d4cda8cbb4eecfe2 to your computer and use it in GitHub Desktop.
Save ahamed/75b36b7f55b1b688d4cda8cbb4eecfe2 to your computer and use it in GitHub Desktop.
Implementation of the debounce hook for ReactJs.
import { useEffect, useState } from 'react';
/**
* useDebounce hook for implementing debounce in react.
* The idea is simple, keep an internal state and update
* the state after a specific delay time. If the given value
* is changed before the delay time then cancel the timeout and
* wait for the delay time once again. And finally return the debounced
* state value.
*
* @source Internet.
* @author Sajeeb Ahamed <[email protected]>
*/
export const useDebounce = <T>(value: T, delay = 300) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
};
// Usage
import { useDebounce } from '@Hooks/useDebounce';
import React, { useEffect, useState } from 'react';
const SearchByKeyword = () => {
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 300);
useEffect(() => {
// You will find the changes once you stop typing and the 300ms delay is completed.
console.log({ debouncedSearch });
}, [debouncedSearch]);
return <input type="text" onChange={(event) => setSearch(event.target.value)} value={search} />;
};
export default SearchByKeyword;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment