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

useStableCallback.ts

22 lines707 Bytes

1import { useLayoutEffect, useRef, useState } from "react";
2​
3/**
4 * Only call it from event handlers and effects; during render it would see the
5 * previous commit's `fn`. The forwarder is created once so its identity does not
6 * depend on the React Compiler, and it keeps no render scope alive: V8 shares one
7 * scope between all closures of a render.
8 */
9export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
10 fn: (...args: Args) => Result,
11): (...args: Args) => Result {
12 const latest = useRef(fn);
13 useLayoutEffect(() => {
14 latest.current = fn;
15 });
16 const [stable] = useState(
17 () =>
18 (...args: Args) =>
19 latest.current(...args),
20 );
21 return stable;