Community JavaScript Snippet

useElementSize With ResizeObserver

Measuring a DOM node's width and height in React without listening to `window.resize`. Uses `ResizeObserver` so it fires for layout-driven changes (sidebar toggling, font load, parent flex) too.

useElementSize With ResizeObserver

Measuring a DOM node's width and height in React without listening to `window.resize`. Uses `ResizeObserver` so it fires for layout-driven changes (sidebar toggling, font load, parent flex) too.

JavaScript
Frontend
3 snippets
react
hooks
performance-optimization
resize-observer
lilykelly

By @lilykelly

April 7, 2026

·

Updated May 18, 2026

977 views

30

4.4 (8)

I always reach for a callback ref over useRef + useEffect for measurement hooks because the timing is cleaner: the callback runs synchronously when React attaches or detaches the node, so I never measure before mount or leak an observer after unmount. The Object.is check inside setSize keeps the state stable when the browser fires noisy ResizeObserver events with the same dimensions, which I have seen happen during scroll-into-view animations. Storing the observer in a ref lets me disconnect cleanly when the consumer swaps elements (a common pattern in conditional rendering).