skip to Main Content

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);
};

3

Answers


  1. 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

    Login or Signup to reply.
  2. Throttling regulates the frequency of function execution, ensuring it doesn’t occur more frequently than a specified interval. However, with useEffect and setTimeout, you can delay a function call to occur after a designated time period.

    For instance, in a search scenario, when typing to search for records with the name "Sau," throttling would limit the function invocation to once per second. On the other hand, using useEffect with setTimeout, the function would be triggered every second.

    and for it to work you should use Loadash

    import _ from 'lodash';
    
    const [query, setQuery] = useState('');
    
    const delayedSearch = useCallback(
        _.debounce((searchQuery) => {
          console.log(`Searching for: ${searchQuery}`);
        }, 1000),
        []
      );
    
    const handleInputChange = (event) => {
      setQuery(event.target.value);
      delayedSearch(event.target.value);
    };
    
    Login or Signup to reply.
  3. You can split and separate the debounce function from useEffect and call that debounce function from it.

    const [query, setQuery] = useState('');
    
    const delayDebounceFn = setTimeout(() => {
          // Perform search operation
          console.log(`Searching for: ${query}`);
       }, 1000); // Delay search by 1 second
    
    useEffect(() => {
      delayDebounceFn ();
    
      return () => clearTimeout(delayDebounceFn);
    }, [query]);
    
    const handleInputChange = (event) => {
        setQuery(event.target.value);
    };
    

    The better way to handle search functions is to use a debounce function(with time delay) for searching. Please check the example code below,

     import { debounce } from 'lodash';
     
     const [inputValue, setInputValue] = useState('');
    
    
      const debouncedSearch = debounce((searchTerm:string) => {
    
        // Perform the search or API call with searchTerm
    
      }, 500);
    
    
      const handleInputChange = (event:any) => {
    
        setInputValue(event.target.value);
    
        debouncedSearch(event.target.value);
    
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search