Skip to content

Instantly share code, notes, and snippets.

@mrcleanandfresh
Forked from stolinski/useMeasure.js
Created February 4, 2020 22:37
Show Gist options
  • Save mrcleanandfresh/2f2def6a020da9a51664f9d91f65f09e to your computer and use it in GitHub Desktop.
Save mrcleanandfresh/2f2def6a020da9a51664f9d91f65f09e 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]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment