Skip to content

Instantly share code, notes, and snippets.

@mwafa
Last active March 8, 2025 14:23
Show Gist options
  • Select an option

  • Save mwafa/4465561755ad9c558b72446605b6121e to your computer and use it in GitHub Desktop.

Select an option

Save mwafa/4465561755ad9c558b72446605b6121e to your computer and use it in GitHub Desktop.
Debounce on React

Basic hook

function useDebounce(state, timeout){
  const [current, setState] = useState(state)

  useEffect(() => {
    const run = setTimeout(() => {
      setState(state)
    }, timeout)
    return () => clearTimeout(run)
  }, [state, timeout])

  return current
}

Simple usage

export default function App() {

  const [title, setTitle] = useState("")
  const lazyTitle = useDebounce(title, 500)

  return (
    <div className="App">
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      <h1>{lazyTitle}</h1>
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment