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

useStableCallback.ts

19 lines632 Bytes

1import { useInsertionEffect, useRef, useState } from "react";
2​
3/** Call only from handlers and effects; render sees the previous commit's fn. */
4export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
5 fn: (...args: Args) => Result,
6): (...args: Args) => Result {
7 const latest = useRef(fn);
8 // Insertion effects run before every layout effect in the commit, so a
9 // child's layout effect already calls this render's fn.
10 useInsertionEffect(() => {
11 latest.current = fn;
12 });
13 const [stable] = useState(
14 () =>
15 (...args: Args) =>
16 latest.current(...args),
17 );
18 return stable;