DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
rohan2734 profile image
rohan2734

why dont we do this in the useEffect?

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

const useDebounce = (data, delay) => {
  const [debouncedData, setDebouncedData] = useState(data);
 var timerID;
  useEffect(() => {

    if(timerID){
       clearTimeout(timerID)
    } 
    console.log("debounce executed");
     timerID = setTimeout(() => {
      setDebouncedData(data);
    }, delay);
   // return () => {
      //clearTimeout(timerID);
    //};
  }, [data.blogTitle, data.blogDescription]);

  return debouncedData;
};

export default useDebounce;


Enter fullscreen mode Exit fullscreen mode

i tried this but the cleartimeout was not working, the timeout was not being cleared, i didnt understand the reason.

can anyone explain?