Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created April 11, 2023 10:20
Show Gist options
  • Save tjinlag/c4d1525a055fd74c44ccf6b3eaf47ed1 to your computer and use it in GitHub Desktop.
Save tjinlag/c4d1525a055fd74c44ccf6b3eaf47ed1 to your computer and use it in GitHub Desktop.
React Custom Hook: useSize
import { useState, useEffect } from "react"
export default function useSize(ref) {
const [size, setSize] = useState({})
useEffect(() => {
if (ref.current == null) return
const observer = new ResizeObserver(([entry]) => setSize(entry.contentRect))
observer.observe(ref.current)
return () => observer.disconnect()
}, [])
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment