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

useStableCallback.ts

16 lines606 Bytes

1import { useCallback, useLayoutEffect, useRef } from "react";
2​
3/**
4 * Only call it from event handlers and effects; during render it would see the
5 * previous commit's `fn`. A `useCallback` result keeps the render scope it was
6 * created in, and V8 shares one scope between all closures of a render.
7 */
8export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
9 fn: (...args: Args) => Result,
10): (...args: Args) => Result {
11 const latest = useRef(fn);
12 useLayoutEffect(() => {
13 latest.current = fn;
14 });
15 return useCallback((...args: Args) => latest.current(...args), []);