From 1a2241c40e10193c5ff7008a7b7b36cc1d855d96 Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Tue, 25 Mar 2025 15:55:45 +0900 Subject: initial commit --- hooks/use-callback-ref.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 hooks/use-callback-ref.ts (limited to 'hooks/use-callback-ref.ts') diff --git a/hooks/use-callback-ref.ts b/hooks/use-callback-ref.ts new file mode 100644 index 00000000..f379a9c3 --- /dev/null +++ b/hooks/use-callback-ref.ts @@ -0,0 +1,27 @@ +import * as React from "react" + +/** + * @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx + */ + +/** + * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a + * prop or avoid re-executing effects when passed as a dependency + */ +function useCallbackRef unknown>( + callback: T | undefined +): T { + const callbackRef = React.useRef(callback) + + React.useEffect(() => { + callbackRef.current = callback + }) + + // https://github.com/facebook/react/issues/19240 + return React.useMemo( + () => ((...args) => callbackRef.current?.(...args)) as T, + [] + ) +} + +export { useCallbackRef } -- cgit v1.2.3