-
Notifications
You must be signed in to change notification settings - Fork 0
useThrottle
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
Throttles a state value so that it updates at most once every specified number of milliseconds. Useful for handling rapid events like scrolling, resizing, or continuous dragging.
The simplest possible implementation.
import { useState, useEffect } from 'react';
import { useThrottle } from 'react-hook-lab';
function BasicThrottle() {
const [scrollY, setScrollY] = useState(0);
const throttledScroll = useThrottle(scrollY);
useEffect(() => {
const handleScroll = () => setScrollY(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div>Throttled Scroll Position (max every 300ms): {throttledScroll}px</div>;
}Customizing the delay for a continuous input slider.
import { useState, useEffect } from 'react';
import { useThrottle } from 'react-hook-lab';
function ColorSlider() {
const [hue, setHue] = useState(0);
const throttledHue = useThrottle(hue, 100); // Update max 10 times a second
useEffect(() => {
// Expensive DOM or canvas operation using throttledHue
document.body.style.backgroundColor = `hsl(${throttledHue}, 100%, 50%)`;
}, [throttledHue]);
return (
<input
type="range" min="0" max="360"
value={hue}
onChange={e => setHue(Number(e.target.value))}
/>
);
}An exhaustive example configuring leading and trailing execution options.
import { useState } from 'react';
import { useThrottle } from 'react-hook-lab';
function AdvancedThrottle() {
const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const throttledPos = useThrottle(
mousePos,
500,
{
leading: false, // Do NOT update immediately on the first movement
trailing: true // DO update one final time after movement stops to catch the final resting position
}
);
return (
<div
onMouseMove={e => setMousePos({ x: e.clientX, y: e.clientY })}
style={{ height: '300px', background: '#eee' }}
>
<p>Raw: {mousePos.x}, {mousePos.y}</p>
<p>Throttled: {throttledPos.x}, {throttledPos.y}</p>
</div>
);
}-
value(Required)- Type:
T - Description: The rapid-changing value to throttle.
- Type:
-
delay- Type:
number - Default:
300 - Description: The throttle window in milliseconds. The value will update maximally once per window.
- Type:
-
options- Type:
UseThrottleOptions - Default:
{} - Description: Configuration object.
-
leading: (boolean, default:true) If true, the value updates immediately on the very first change. -
trailing: (boolean, default:true) If true, the value updates one final time after the delay window ends to ensure it captures the absolute latest state.
-
- Type:
Returns T:
- The throttled value.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM