Skip to content

Instantly share code, notes, and snippets.

@chriskoelle
Last active February 22, 2021 18:00
Show Gist options
  • Save chriskoelle/bf5a25f12e081d3f6e278ba83a85f743 to your computer and use it in GitHub Desktop.
Save chriskoelle/bf5a25f12e081d3f6e278ba83a85f743 to your computer and use it in GitHub Desktop.
React useSize hook
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