useThrottledCallback
Throttle a function with cancel and flush.
Import
TypeScript
import { useThrottledCallback } from '@/hooks';API
Signature
useThrottledCallback(fn, delay | options) → fn & { cancel, flush }
When to use
Use useThrottledCallback instead of re-implementing the same pattern in multiple components.
SSR / Next.js
SSR-safe. Timers and rAF only run after mount / interactions.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useThrottledCallbackEditor
function OnScroll() { const onScroll = useThrottledCallback(() => { console.log(window.scrollY); }, 200); return <div onScroll={onScroll} style={{ height: 200, overflow: 'auto' }}>…</div>; }
Preview
Implementation source
Full library source for useThrottledCallback — copy into your project when you are not installing a package yet.
hooks/performance/useThrottledCallback.ts
import { useEffect, useMemo, useRef } from 'react';
import type { ThrottleOptions } from '../types';
import { useLatest } from '../utility/useLatest';
import { useUnmount } from '../utility/useUnmount';
export type ThrottledFunction<TArgs extends unknown[]> = ((
...args: TArgs
) => void) & {
cancel: () => void;
flush: () => void;
};
/**
* Throttles a callback (rate limits invocations).
*/
export function useThrottledCallback<TArgs extends unknown[]>(
fn: (...args: TArgs) => void,
delayOrOptions: number | ThrottleOptions = 300,
): ThrottledFunction<TArgs> {
const options: ThrottleOptions =
typeof delayOrOptions === 'number'
? { delay: delayOrOptions }
: delayOrOptions;
const { delay = 300, leading = true, trailing = true } = options;
const fnRef = useLatest(fn);
const lastInvokeRef = useRef(0);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastArgsRef = useRef<TArgs | null>(null);
const clearTimer = () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
const throttled = useMemo(() => {
const wrapped = ((...args: TArgs) => {
const now = Date.now();
const remaining = delay - (now - lastInvokeRef.current);
lastArgsRef.current = args;
if (remaining <= 0 || remaining > delay) {
clearTimer();
if (leading || lastInvokeRef.current !== 0) {
lastInvokeRef.current = now;
fnRef.current(...args);
lastArgsRef.current = null;
} else {
lastInvokeRef.current = now;
}
} else if (trailing && !timerRef.current) {
timerRef.current = setTimeout(() => {
lastInvokeRef.current = leading === false ? 0 : Date.now();
timerRef.current = null;
if (lastArgsRef.current) {
fnRef.current(...lastArgsRef.current);
lastArgsRef.current = null;
}
}, remaining);
}
}) as ThrottledFunction<TArgs>;
wrapped.cancel = () => {
clearTimer();
lastArgsRef.current = null;
};
wrapped.flush = () => {
if (lastArgsRef.current) {
fnRef.current(...lastArgsRef.current);
lastArgsRef.current = null;
}
clearTimer();
lastInvokeRef.current = Date.now();
};
return wrapped;
}, [delay, leading, trailing]);
useEffect(() => clearTimer, [delay, leading, trailing]);
useUnmount(clearTimer);
return throttled;
}
Copy-paste example
useThrottledCallback.example.tsx
'use client';
import { useThrottledCallback } from '@/hooks';
export function OnScroll() {
const onScroll = useThrottledCallback(() => {
console.log(window.scrollY);
}, 200);
return <div onScroll={onScroll} style={{ height: 200, overflow: 'auto' }}>…</div>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Stable callbacks prevent child re-renders. Always cancel debounce on unmount (handled for you).
- Source of truth: open
hooks/performance/useThrottledCallback.tsfor implementation details