typescriptintermediate
useThrottledValue Hook
Throttles a rapidly changing value to update at most once per specified interval.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useRef } from 'react';
export function useThrottledValue<T>(value: T, intervalMs: number): T {
const [throttled, setThrottled] = useState(value);
const lastUpdated = useRef(Date.now());
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
const now = Date.now();
const elapsed = now - lastUpdated.current;
if (elapsed >= intervalMs) {
lastUpdated.current = now;
setThrottled(value);
} else {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
lastUpdated.current = Date.now();
setThrottled(value);
}, intervalMs - elapsed);
}
return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
}, [value, intervalMs]);
return throttled;
}
// Usage:
// const throttledMousePos = useThrottledValue(mousePosition, 100);Use Cases
- Scroll position tracking
- Mouse move handlers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useThrottle Hook for Rate Limiting
Throttle rapidly-firing values like scroll or resize events with a configurable delay hook.
Best for: Scroll position tracking
#react#hooks
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptintermediate
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
Best for: Feed pagination
#infinite-scroll#intersection-observer