reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
27 lines (26 loc) • 800 B
JavaScript
import { useState, useLayoutEffect, useRef } from "react";
export function useElementSize() {
const ref = useRef(null);
const [size, setSize] = useState({ width: 0, height: 0 });
useLayoutEffect(() => {
if (!ref.current)
return;
const updateSize = () => {
if (ref.current) {
setSize({
width: ref.current.offsetWidth,
height: ref.current.offsetHeight,
});
}
};
updateSize();
window.addEventListener("resize", updateSize);
return () => window.removeEventListener("resize", updateSize);
}, []);
return [ref, size];
}
/*
Example:
const [ref, { width, height }] = useElementSize();
<div ref={ref}>Size: {width}x{height}</div>
*/