DEV Community

Vladimir Nikitin
Vladimir Nikitin

Posted on • Edited on

React useThrottle hook with usage example

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

Top comments (3)

Collapse
 
a7mad1112 profile image
Ahmed Alawneh

Great post! Your explanation of throttle is clear and concise. 👏

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

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

const throttledValue = useThrottle(value, 1000)
Enter fullscreen mode Exit fullscreen mode