Search code examples
reactjsreact-hooksdebouncing

What is the difference when using throttle and useeffect settimeout for search


I am using useEffect and its working fine, but I am aked to use debounce insted. Should I just make the useEffect into a seprate/ reusable function?

const [query, setQuery] = useState('');

useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      // Perform search operation
      console.log(`Searching for: ${query}`);
   }, 1000); // Delay search by 1 second

  return () => clearTimeout(delayDebounceFn);
}, [query]);

const handleInputChange = (event) => {
    setQuery(event.target.value);
};

Solution

  • To answer your question: Yes.

    Go for useEffect function, if data to be fetched or manipulated when dependent object changes

    useEffect(<function>, <dependency>)
    
    useEffect(() => {
      //Runs only on the first render
    }, []);
    
    useEffect(() => {
       //Runs when the dependent object changes.
    }, [dependent object (like queryparameter]);
    

    but in cases like, user is typing in searchbar then it make sense to delay the fetching of records for ,let's say, microseconds.

    function debounce_leading(func, timeout = 300){
      let timer;
      return (...args) => {
        if (!timer) {
          func.apply(this, args);
        }
        clearTimeout(timer);
        timer = setTimeout(() => {
          timer = undefined;
        }, timeout);
      };
    }
    

    Hope this helps