DEV Community

loading...

React useThrottle hook with usage example

Vladimir Nikitin
Frontend developer working with React and TypeScript
Updated on ・1 min read

Throttling is a technique, where a given function runs only once at a specified period of time

Throttling could be used in scenarios, where our code does expensive CPU/Network tasks on frequently fired events:

  • Listening to HTML Input element change
  • Listening to window resize or scroll
  • Listening to mouse cursor position change

Code

This is a React hook to work with throttling

Example of usage: listening to HTML input element change

CodeSandbox example

Live demo of the previous useThrottle hook usage in CodeSandbox. Throttled value updates only once at interval (500ms by default)

Links: CodeSandbox demo | GitHub repo

Discussion (2)

Collapse
nano1709 profile image
Ignacio Vargas • Edited

Good post!
Question: So it's 500ms by default, but can it be change to other value/response time and so how?

Collapse
loonywizard profile image
Vladimir Nikitin Author

Thanks! Yes, you could pass second argument to useThrottle hook, example for 1000ms:

const throttledValue = useThrottle(value, 1000)
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app