From 75b6d3db74852de57e97fc400b9b7ed0f2a68d40 Mon Sep 17 00:00:00 2001 From: Muhammad Eko Date: Tue, 1 Oct 2024 15:27:42 +0700 Subject: [PATCH] progress --- src/lib/hooks/dimension.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/lib/hooks/dimension.ts b/src/lib/hooks/dimension.ts index e69de29..78891d6 100644 --- a/src/lib/hooks/dimension.ts +++ b/src/lib/hooks/dimension.ts @@ -0,0 +1,21 @@ +import { RefObject, useMemo, useSyncExternalStore } from "react" + +function subscribe(callback: (e: Event) => void) { + window.addEventListener("resize", callback) + return () => { + window.removeEventListener("resize", callback) + } +} + +function useDimensions(ref: RefObject) { + const dimensions = useSyncExternalStore( + subscribe, + () => JSON.stringify({ + width: ref.current?.offsetWidth ?? 0, + height: ref.current?.offsetHeight ?? 0, + }), + ) + return useMemo(() => JSON.parse(dimensions), [dimensions]) +} + +export { useDimensions } \ No newline at end of file