I noticed another answer mentioning to use a ResizeObserver, but the answer is incomplete, so I'd like to add my own.
Using useEffect
You can create a ResizeObserver
inside a useEffect
-hook, and then do what you want to do when the element changes its size. Remember to disconnect from the resizeObserver
in the cleanup function.
useEffect(() => {
if (!elementRef.current) return;
const resizeObserver = new ResizeObserver(() => {
// Do what you want to do when the size of the element changes
});
resizeObserver.observe(elementRef.current);
return () => resizeObserver.disconnect(); // clean up
}, []);
Using useCallback
As mentioned in the comments, it's also possible to use useCallback
instead of useEffect
.
You can create a ResizeObserver
inside a useCallback
-hook, and then do what you want to do when the element changes its size. React has an example on how to measure a DOM node.
const elementRef = useCallback(node => {
if (!node) return;
const resizeObserver = new ResizeObserver(() => {
// Do what you want to do when the size of the element changes
});
resizeObserver.observe(node);
}, []);