JAVASCRIPT

Optimize React Input with a Custom `useDebounce` Hook

Implement a `useDebounce` hook in React to delay state updates or function calls, significantly improving performance for search inputs and frequent events.

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 SearchInput() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500);

//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       // Perform API call or heavy computation with debouncedSearchTerm
//       console.log('Searching for:', debouncedSearchTerm);
//     }
//   }, [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 time has passed without further changes. This is incredibly useful for optimizing performance in scenarios like search bars, where you don't want to trigger an API call or expensive operation on every keystroke, but rather after the user has paused typing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs