Last active
February 22, 2021 18:00
-
-
Save chriskoelle/bf5a25f12e081d3f6e278ba83a85f743 to your computer and use it in GitHub Desktop.
React useSize hook
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, useState, useEffect } from 'react'; | |
/** | |
* Get the size of a component on render and resize | |
* | |
* @example | |
* const sizeRef = useRef(null); | |
* const { height, width } = useSize(sizeRef) | |
* | |
* <div ref={sizeRef}> | |
* | |
* @param {RefObject} ref Reference to the component | |
*/ | |
const useSize = (ref) => { | |
const [size, setSize] = useState({ width: 0, height: 0 }); | |
const observer = useRef(null); | |
useEffect(() => { | |
observer.current = new ResizeObserver((entries = []) => { | |
entries.forEach((entry) => { | |
const { width, height } = entry.contentRect; | |
setSize({ width, height }); | |
}); | |
}); | |
if (ref.current) observer.current.observe(ref.current); | |
return () => { | |
if (observer.current) observer.current.disconnect(); | |
}; | |
}, [ref]); | |
return size; | |
}; | |
export default useSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment