Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active August 4, 2021 16:07
Show Gist options
  • Save sekoyo/869f458d5f034c8a4f9e067d15f7d682 to your computer and use it in GitHub Desktop.
Save sekoyo/869f458d5f034c8a4f9e067d15f7d682 to your computer and use it in GitHub Desktop.
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