typescriptintermediate

useThrottledValue Hook

Throttles a rapidly changing value to update at most once per specified interval.

typescript
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.