JAVASCRIPT

Efficient Debouncing for React Inputs with `useDebounce`

Learn to create a custom `useDebounce` React hook to delay state updates, optimizing performance for search inputs and preventing excessive function calls.

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

// How to use it:
// function SearchBar() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay

//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Fetching data for:', debouncedSearchTerm);
//       // Perform API call or expensive operation here
//     }
//   }, [debouncedSearchTerm]);

//   return (
//     <input
//       type="text"
//       placeholder="Search..."
//       value={searchTerm}
//       onChange={(e) => setSearchTerm(e.target.value)}
//     />
//   );
// }
How it works: The `useDebounce` hook takes a value and a delay. It sets a `debouncedValue` state which only updates after the specified `delay` has passed since the `value` last changed. This is achieved using `setTimeout` and `clearTimeout` within a `useEffect` hook, preventing immediate re-execution of a function (like an API call) every time the input value changes, thus optimizing performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs