Skip to content

Instantly share code, notes, and snippets.

@stolinski
Created April 18, 2019 18:16
Show Gist options
  • Save stolinski/1fecfb2677e0b2deda9039608fecf5d8 to your computer and use it in GitHub Desktop.
Save stolinski/1fecfb2677e0b2deda9039608fecf5d8 to your computer and use it in GitHub Desktop.
useMeasure - taken from React Spring example
import { useRef, useState, useEffect } from 'react'
import ResizeObserver from 'resize-observer-polyfill'
export default function useMeasure() {
const ref = useRef()
const [bounds, set] = useState({ left: 0, top: 0, width: 0, height: 0 })
const [ro] = useState(() => new ResizeObserver(([entry]) => set(entry.contentRect)))
useEffect(() => (ro.observe(ref.current), ro.disconnect), [])
return [{ ref }, bounds]
}
@yushanwebdev
Copy link

yushanwebdev commented Oct 9, 2021

useEffect needs to update like this.

useEffect(() => {
   ro.observe(ref.current);
   return () => ro.unobserve(ref.current);
}, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment