Debouncing in React

useDebounce Hook

Example

Type quickly: the "API call" only happens 500 ms after you stop typing.

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);   // typing again cancels the previous timer
  }, [value, delay]);
  return debounced;
}

export default function App() {
  const [text, setText] = useState('');
  const query = useDebounce(text, 500);

  useEffect(() => {
    if (query) console.log('API call: /search?q=' + query);
  }, [query]);

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Search..." />
      <p>Typed: {text} | Searched: {query}</p>
    </div>
  );
}

Result