Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React useSizeObserver
import { useEffect, useRef } from 'react'
export function useSizeObserver(
elRef: React.RefObject<HTMLElement | null>,
onChange: (width: number, height: number) => void,
shouldObserve = true
) {
const onChangeRef = useRef(onChange)
onChangeRef.current = onChange
useEffect(() => {
const el = elRef.current
if (shouldObserve && el) {
const { width, height } = el.getBoundingClientRect()
onChangeRef.current(width, height)
const resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
const { width, height } = entries[0].contentRect
onChangeRef.current(width, height)
})
resizeObserver.observe(el)
return () => {
resizeObserver.disconnect()
}
}
}, [shouldObserve])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment