summaryrefslogtreecommitdiff
path: root/hooks/use-callback-ref.ts
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
commite0dfb55c5457aec489fc084c4567e791b4c65eb1 (patch)
tree68543a65d88f5afb3a0202925804103daa91bc6f /hooks/use-callback-ref.ts
3/25 까지의 대표님 작업사항
Diffstat (limited to 'hooks/use-callback-ref.ts')
-rw-r--r--hooks/use-callback-ref.ts27
1 files changed, 27 insertions, 0 deletions
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<T extends (...args: never[]) => 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 }