This content originally appeared on DEV Community and was authored by Rajesh Royal
I could have use the Loadash naaahh... 🙅♀️ Loadash is too expensive.
So here is how you can make your own debounce effect with custom hooks in react js.
useDebouncedEffect.tsx
import { useEffect } from "react";
export const useDebouncedEffect = (effect: any, deps: any[], delay: number) => {
useEffect(() => {
const handler = setTimeout(() => effect(), delay);
return () => clearTimeout(handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...(deps || []), delay]);
};
To use this hook simply call It like this:
import { useDebouncedEffect } from "./useDebouncedEffect";
// debounce search onchange
// eslint-disable-next-line react-hooks/exhaustive-deps
useDebouncedEffect(
() => {
// function which will be running on effect, in our case when something changes in search box.
changeSearchState();
},
// this is the dependency, if it changes it will trigger the debounce again
[search],
// time to wait before effect runs
debounceTimeInMilliseconds
);
credit - from Internet [R&D]
Thanks for reading this far 😃
Fact: Do you know you can hit that follow button on top right and make it disappear 😄. Do not believe me try once 👍
This content originally appeared on DEV Community and was authored by Rajesh Royal
Rajesh Royal | Sciencx (2022-01-24T16:41:00+00:00) How to make a custom Debounce hook in react js. Retrieved from https://www.scien.cx/2022/01/24/how-to-make-a-custom-debounce-hook-in-react-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.