useStableCallback
Returns a function whose identity never changes but that always calls your latest callback. It lets you pass handlers to memoized children, dependency arrays and long-lived subscriptions without re-creating them or reading stale props and state.
When to use it
- Passing an event handler to a
React.memochild without it re-rendering whenever the handler's dependencies change. - Subscribing to timers, sockets, observers or DOM events once, while the handler still reads current props and state.
- Calling an optional callback prop (
onChange?) without?.at every call site. - Keeping an effect's dependency array small without silencing the linter.
Demo
Edit the code below — the preview re-runs live. Open the Console tab to see which rows render and when the timer starts.
Loading demo…
Signature
type AnyFunction = (...args: never[]) => unknown;
interface UseStableCallback {
<T extends AnyFunction>(callback: T): T;
<T extends AnyFunction>(
callback: T | null | undefined
): (...args: Parameters<T>) => ReturnType<T> | undefined;
}
const useStableCallback: UseStableCallback;
| Parameter | Type | Description |
|---|---|---|
callback | T | null | undefined | The function to call. May be omitted for no-op. |
Returns: a function with the same parameters and return type as
callback, and a permanent identity. If callback can be null or
undefined, the return type also includes undefined.
Usage notes
- Stable identity. The returned function is the same on every render, so it never triggers a re-render of a memoized child and never re-runs an effect that lists it as a dependency.
- Always the latest callback. The newest
callbackis stored after each render, in a layout effect, so it is already in place by the time effects and event handlers run. Callbacks passed in an earlier render are never called. - Not for render. The callback is not updated during render, so calling the returned function while rendering would run the previous render's callback. Call it from event handlers, effects, timers and other callbacks.
- Arguments,
thisand results pass through. Return values, thrown errors andthisare forwarded unchanged, and the type ofcallbackis preserved. - Optional callbacks. Pass
undefinedornulland the returned function simply does nothing and returnsundefined, which is handy for optional props. - Effects are not re-run. Because the identity never changes, an effect that depends on the function does not re-run when the callback's own dependencies change. If you want that, depend on those values directly.
- vs
useLatest.useLatestgives you a ref to any value;useStableCallbackwraps a function so you can pass it around and call it directly. - vs
useDebouncedCallback. To also delay or cancel calls, useuseDebouncedCallback, which is stable and latest-aware too. - Safe under React
StrictModeand server rendering (no layout-effect warning), and works on React 18 and 19.
Example
const handleSelect = useStableCallback((id: string) => {
setSelected(id);
analytics.track(id, filter);
});
return <MemoList onSelect={handleSelect} />;
Hook source
View useStableCallback source
useStableCallback sourceuse-stable-callback.ts
import { useCallback, useRef } from "react";
import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect";
type AnyFunction = (...args: never[]) => unknown;
/**
* The signature of {@link useStableCallback}: the wrapped function keeps its
* type, and gains `undefined` in its return type when `callback` can be
* `null` or `undefined`.
*/
export interface UseStableCallback {
<T extends AnyFunction>(callback: T): T;
<T extends AnyFunction>(
callback: T | null | undefined
): (...args: Parameters<T>) => ReturnType<T> | undefined;
}
/**
* Returns a function with a permanent identity that always calls the latest
* `callback`.
*
* Use it to pass a handler to a memoized child, a dependency array or a
* long-lived subscription (timers, listeners, observers) without
* re-creating or re-subscribing it on every render, and without reading
* stale props or state. Arguments, `this` and the return value are passed
* through, so it can wrap any function without changing its type.
*
* `callback` may also be `null` or `undefined`, which is handy for optional
* props: the returned function then does nothing and returns `undefined`.
*
* The latest `callback` is stored in a layout effect, so it is in place
* before effects and event handlers run, but it is not updated during
* render. Call the returned function from event handlers, effects and other
* callbacks, not while rendering. For reading a value rather than calling a
* function, see `useLatest`.
*
* @typeParam T - The type of the wrapped function.
* @param callback - The function to call, or `null`/`undefined` for none.
* @returns A stable function with the same signature as `callback`. If
* `callback` can be `null` or `undefined`, its return type also includes
* `undefined`.
*
* @example
* ```tsx
* // A memoized child never re-renders because of the handler
* const handleSelect = useStableCallback((id: string) => {
* setSelected(id);
* analytics.track(id, filter);
* });
*
* return <MemoList onSelect={handleSelect} />;
* ```
*
* @example
* ```tsx
* // Subscribe once, always call the latest handler
* const onMessage = useStableCallback((message: string) => {
* setLog((log) => [...log, `${user}: ${message}`]);
* });
*
* useEffect(() => {
* const socket = connect(url);
* socket.on("message", onMessage);
* return () => socket.close();
* }, [url, onMessage]);
* ```
*
* @example
* ```tsx
* // Optional prop: safe to call without `?.`
* const notify = useStableCallback(props.onChange);
* ```
*
* For a live, editable example, see the [useStableCallback docs page](https://altalyst-solutions.github.io/hookify/hooks/use-stable-callback).
*/
export const useStableCallback = (<T extends AnyFunction>(
callback: T | null | undefined
) => {
const ref = useRef(callback);
useIsomorphicLayoutEffect(() => {
ref.current = callback;
});
return useCallback(function (this: unknown, ...args: Parameters<T>) {
return ref.current?.apply(this, args);
}, []);
}) as UseStableCallback;