Skip to content

useThrottledValue

Watches a value and returns a throttled version of it updated at a given delay.

Installation

npx rabbithook@latest add use-throttled-value

Usage

App.tsx
import useThrottledValue from "@/hooks/use-throttled-value";
function Component() {
const [state, setState] = useState("");
const throttledState = useThrottledValue(state, 2 * 1000 /* 2 seconds */);
return (
<>
<p>State: {state}</p>
<p>Throttled State: {throttledState}</p>
<input value={state} onChange={event => setState(event.target.value)} />
</>
);
}

Code

use-throttled-value.ts
import { useEffect, useRef, useState } from 'react';
function useThrottledValue<T>(value: T, delay: number): T {
const [throttledValue, setThrottledValue] = useState(value);
const lastExecutedRef = useRef(0);
useEffect(() => {
const now = Date.now();
const timeSinceLastExecution = now - lastExecutedRef.current;
if (timeSinceLastExecution >= delay) {
setThrottledValue(value);
lastExecutedRef.current = now;
} else {
const timeoutId = setTimeout(() => {
setThrottledValue(value);
lastExecutedRef.current = Date.now();
}, delay - timeSinceLastExecution);
return () => clearTimeout(timeoutId);
}
}, [value, delay]);
return throttledValue;
}
export default useThrottledValue;