How to use the React useEffect hook with debounce?

Estimated read time 2 min read

The useEffect hook in React allows you to perform side effects in your component, such as fetching data from an API or subscribing to a WebSocket. Sometimes, you may want to debounce the side effect so that it only runs after a certain amount of time has passed since the last trigger. Here’s an example of how to use the useEffect hook with debounce in React:

import React, { useState, useEffect } from 'react';
import debounce from 'lodash.debounce';

function MyComponent(props) {
  const [searchTerm, setSearchTerm] = useState('');

  const debouncedSearch = debounce((term) => {
    // Perform your side effect here, e.g. fetch data from an API
    console.log('Searching for:', term);
  }, 1000);

  useEffect(() => {
    debouncedSearch(searchTerm);
  }, [searchTerm]);

  function handleSearch(event) {
    const term = event.target.value;
    setSearchTerm(term);
  }

  return (
    <div>
      <input type="text" onChange={handleSearch} />
      {/* rest of your component code */}
    </div>
  );
}

In this example, we define a component called MyComponent that has an input field for searching. We use the useState hook to keep track of the search term, and we define a debounced version of the search function using the lodash.debounce library. The debounced function is called with a delay of 1000ms (1 second) after the last trigger.

We use the useEffect hook to call the debounced search function whenever the searchTerm state changes. This ensures that the side effect is only triggered after a delay, even if the user types quickly or changes the search term frequently.

Finally, we define a handleSearch function that updates the searchTerm state with the current input value.

Note that we import the debounce function from the lodash.debounce library, which provides an efficient and easy way to debounce functions in JavaScript.

Using the useEffect hook with debounce can help improve the performance and user experience of your React app, especially when dealing with expensive or frequent side effects.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply