Last active
July 28, 2022 06:55
-
-
Save sekoyo/c8579667e8a8bd7817c1b4d5b274eb4c to your computer and use it in GitHub Desktop.
useResizeObserver hook for React
This file contains 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 { useRef, useCallback, useEffect, useState } from 'react'; | |
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer'; | |
const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill; | |
export default function useResizeObserver() { | |
const [size, setSize] = useState({ width: 0, height: 0 }); | |
const resizeObserver = useRef(null); | |
const onResize = useCallback(entries => { | |
const { width, height } = entries[0].contentRect; | |
setSize({ width, height }); | |
}, []); | |
const ref = useCallback( | |
node => { | |
if (node !== null) { | |
if (resizeObserver.current) { | |
resizeObserver.current.disconnect(); | |
} | |
resizeObserver.current = new ResizeObserver(onResize); | |
resizeObserver.current.observe(node); | |
} | |
}, | |
[onResize] | |
); | |
useEffect(() => () => { | |
resizeObserver.current.disconnect(); | |
}, []); | |
return { ref, width: size.width, height: size.height }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: