excalidraw/packages/excalidraw/hooks/useStableCallback.ts
Ryan Di 550a388b2b
feat: command palette (#7804)
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2024-03-28 16:16:32 +00:00

19 lines
473 B
TypeScript

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;
};