useThrottle

Performance

A React hook that limits the rate at which a value can update by ensuring a minimum time interval between updates, useful for handling high-frequency events like scroll or resize.

Demo

1. Mouse Movement

Move your mouse over this area. Position updates are throttled to 100ms intervals.
Current: x: 0, y: 0
Throttled: x: 0, y: 0

2. Window Resize

Resize your browser window. Size updates are throttled to 500ms intervals.
Current Size
0px × 0px
Throttled Size
0px × 0px
Update Log

Installation

npm install @thibault.sh/hooks

Usage

import { useThrottle } from "@thibault.sh/hooks";

function MouseTracker() {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const throttledPosition = useThrottle(position, 100);

  useEffect(() => {
    const handleMouseMove = (e) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };

    window.addEventListener("mousemove", handleMouseMove);
    return () => window.removeEventListener("mousemove", handleMouseMove);
  }, []);

  return (
    <div>
      <div>Current: x: {position.x}, y: {position.y}</div>
      <div>Throttled: x: {throttledPosition.x}, y: {throttledPosition.y}</div>
    </div>
  );
}

API Reference

Returns

The throttled value

Parameters

value

The value to throttle. This can be any type of value (string, number, object, etc.). The hook will return a new value of the same type at most once per interval.

interval

The minimum time in milliseconds that must pass between value updates. A typical value is 100ms for mouse events or 500ms for resize events.

Return Value

Returns the throttled value. The value will only update once within the specified interval, even if the input value changes more frequently.

Type: T (same type as input value)

Features

Rate Limiting

Enforces a maximum update frequency for values, ensuring consistent performance even with rapidly changing inputs.

Event Optimization

Perfect for optimizing high-frequency events like scroll, resize, or mousemove, reducing unnecessary renders and computations.

Type Safety

Full TypeScript support with generics, ensuring type safety between the input value and the throttled output.

Memory Efficient

Properly manages internal timers and cleanup on unmount, preventing memory leaks and ensuring smooth performance.

Throttle vs Debounce

While both throttle and debounce are used to control the rate of updates, they serve different purposes:

Throttle

Ensures updates occur at a consistent rate by enforcing a minimum time interval between updates. Useful for maintaining a steady stream of updates (e.g., game loop, progress updates).

Debounce

Waits for a pause in updates before applying the latest value. Useful when you only care about the final value after changes stop (e.g., search input, form validation).