Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 24, 2022 04:41 pm GMT

How to make a custom Debounce hook in react js

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


Original Link: https://dev.to/rajeshroyal/how-to-make-a-custom-debounce-hook-in-react-js-4gcc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To