This commit is contained in:
Muhammad Eko 2024-10-01 15:27:42 +07:00
parent f4cc284fb5
commit 75b6d3db74
1 changed files with 21 additions and 0 deletions

View File

@ -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<HTMLElement>) {
const dimensions = useSyncExternalStore(
subscribe,
() => JSON.stringify({
width: ref.current?.offsetWidth ?? 0,
height: ref.current?.offsetHeight ?? 0,
}),
)
return useMemo(() => JSON.parse(dimensions), [dimensions])
}
export { useDimensions }