← Back to all snippets
JAVASCRIPT

Efficiently Debounce React State Updates

Optimize performance by debouncing any value in React, preventing excessive re-renders or API calls for rapidly changing inputs like search queries.

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

// Example Usage:
// function SearchBar() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500);

//   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 delays updating a value until a specified `delay` has passed without any new changes to the original `value`. This is crucial for optimizing performance in scenarios like search inputs where you want to wait for the user to finish typing before making an API request, or for resizing events to avoid excessive recalculations. It uses `setTimeout` to defer the update and `clearTimeout` in the cleanup function to reset the timer if the value changes before the delay expires.

Need help integrating this into your project?

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

Hire DigitalCodeLabs