Dec. 12, 2022

Learn to debounce search boxes with lodash in ReactJS

Optimizing Search Performance with Lodash and ReactJS: Implementing Debouncing Techniques

To use a functional component with debounced search input, you can use the useRef and useEffect hooks to create a debounced version of the performSearch function. Here's an example of how you might do that:

import React, { useRef, useEffect } from 'react';
import debounce from 'lodash/debounce';

const MyComponent = (props) => {
  const [searchTerm, setSearchTerm] = React.useState('');
  const debouncedSearch = useRef(debounce(performSearch, 500)).current;

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

  function onSearchChange(event) {
    setSearchTerm(event.target.value);
  }

  function performSearch(searchTerm) {
    // perform the search here
  }

  return (
    <input
      type="text"
      onChange={onSearchChange}
      value={searchTerm}
    />
  );
};

In this example, the useRef hook is used to create a debounced version of the performSearch function, and the useEffect hook is used to call the debounced function whenever the searchTerm state variable changes. This allows the functional component to have the same behavior as the class-based example from earlier, but using a functional component and hooks.