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