# useThrottledCallback

Returns a throttled version of `callback`: it runs right away, then at most once every `intervalMs` while calls keep coming, and once more at the end with the arguments of the last call, so the final value is never lost. The returned function is stable and always runs the latest `callback`.

A pending call is dropped on unmount (call `flush` first to keep it) and when `intervalMs` changes.

## Import

```ts
import { useThrottledCallback } from '@vincent.ri/react-tils'
// or only this hook
import { useThrottledCallback } from '@vincent.ri/react-tils/useThrottledCallback'
```

## Usage

```ts
const sendCursor = useThrottledCallback((x: number, y: number) => socket.send({ x, y }), 100)
return <div onPointerMove={(e) => sendCursor(e.clientX, e.clientY)} />
```

## When to use it

Work that should keep happening during a burst, not only after it: live search results while typing, saving a slider's position, sending "typing…" or cursor positions to a server, analytics for scroll depth.

## When not to

It should run once after the user stops (autosave a draft, validate); use `useDebouncedCallback`. To follow scroll or size, use `useWindowScroll`, `useElementScroll`, or `useElementSize`, which already avoid extra re-renders. For drawing on every frame, use `useAnimationFrame`.

## API

```ts
function useThrottledCallback<A extends unknown[]>(callback: (...args: A) => void, intervalMs: number): ThrottledFunction<A>
```

| Parameter | Description |
| --- | --- |
| `callback` | The function to throttle. Can change every render. |
| `intervalMs` | Run at most once per this many milliseconds. |

**Returns** The throttled function, with `cancel`, `flush`, and `pending`.

### Types

```ts
/** Same shape as a debounced function: callable, with `cancel`, `flush`, and `pending`. */
export type ThrottledFunction<A extends unknown[]> = DebouncedFunction<A>;
```

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useThrottleFn`, `useThrottleCallback`, `useThrottle`.

---

268 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useThrottledCallback.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useThrottledCallback/
Previous: [useDebouncedValue](https://vincentri.github.io/react-tils/hooks/useDebouncedValue.md)
Next: [useAnimationFrame](https://vincentri.github.io/react-tils/hooks/useAnimationFrame.md)
