blob: 9920a73f63e8cbc18bd1e2789a977031ebcaee00 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import { useRef } from "react";
/**
* Returns a stable function of the same type.
*/
export const useStableCallback = <T extends (...args: any[]) => any>(
userFn: T,
) => {
const stableRef = useRef<{ userFn: T; stableFn?: T }>({ userFn });
stableRef.current.userFn = userFn;
if (!stableRef.current.stableFn) {
stableRef.current.stableFn = ((...args: any[]) =>
stableRef.current.userFn(...args)) as T;
}
return stableRef.current.stableFn as T;
};
|