Created
March 18, 2022 17:54
-
-
Save dominictobias/eb207c39ddb6a4c77800a4d0dfa5f9b8 to your computer and use it in GitHub Desktop.
Resize observer hook for react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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