Skip to content

Commit 50a1209

Browse files
committed
feat: add useRefWidth hook
1 parent ebebfa2 commit 50a1209

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/hooks/useRefWidth.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"use client"
2+
3+
import { type RefObject, useEffect, useState } from "react"
4+
5+
import { useEventListener } from "./useEventListener"
6+
7+
export const useRefWidth = (
8+
ref: RefObject<HTMLElement>,
9+
padding: number = 0
10+
): number => {
11+
const [width, setWidth] = useState(0)
12+
13+
const updateWidth = () => {
14+
if (ref.current) {
15+
const rect = ref.current.getBoundingClientRect()
16+
setWidth(Math.max(0, rect.width - padding))
17+
}
18+
}
19+
20+
// Use the internal useEventListener for window resize
21+
useEventListener("resize", updateWidth)
22+
23+
useEffect(() => {
24+
// Initial measurement
25+
updateWidth()
26+
27+
// Create ResizeObserver for more accurate monitoring
28+
const resizeObserver = new ResizeObserver(updateWidth)
29+
if (ref.current) {
30+
resizeObserver.observe(ref.current)
31+
}
32+
33+
return () => {
34+
resizeObserver.disconnect()
35+
}
36+
}, [ref, padding])
37+
38+
return width
39+
}

0 commit comments

Comments
 (0)