Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useStableCallback.ts

22 lines944 Bytes

1import { useCallback, useLayoutEffect, useRef } from "react";
2​
3/**
4 * Returns a function with a fixed identity that always calls the latest `fn`.
5 * Only call it from event handlers and effects; during render it would see the
6 * previous commit's `fn`.
7 *
8 * Use it for event handlers in large, long-lived components. A `useCallback`
9 * result keeps the render scope it was created in, and V8 shares one scope
10 * between all closures of a render. When several memoized handlers change at
11 * different times, each keeps an older scope holding older copies of the
12 * others, and old renders pile up for as long as the component is mounted.
13 */
14export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
15 fn: (...args: Args) => Result,
16): (...args: Args) => Result {
17 const latest = useRef(fn);
18 useLayoutEffect(() => {
19 latest.current = fn;
20 });
21 return useCallback((...args: Args) => latest.current(...args), []);