Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Created March 18, 2022 17:54
Show Gist options
  • Save sekoyo/eb207c39ddb6a4c77800a4d0dfa5f9b8 to your computer and use it in GitHub Desktop.
Save sekoyo/eb207c39ddb6a4c77800a4d0dfa5f9b8 to your computer and use it in GitHub Desktop.
Resize observer hook for react
import { useEffect, useRef, useState } from 'react'
export function useResizeObserver<E extends Element>() {
const ref = useRef<E>(null)
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
useEffect(() => {
if (!ref.current) {
return () => {}
}
const observer = new ResizeObserver(([el]) => {
const { width, height } = el.contentRect
setWidth(width)
setHeight(height)
})
observer.observe(ref.current)
return () => {
observer.disconnect()
}
}, [])
return { ref, width, height }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment