React Hooks Recipes/Measure an element’s size

Use a ref plus ResizeObserver.

Section: UI Recipes

Measure an element’s size

tsx
tsx
useEffect(() => {
  if (!ref.current) return;
  const observer = new ResizeObserver(([entry]) => {
    setSize(entry.contentRect);
  });
  observer.observe(ref.current);
  return () => observer.disconnect();
}, []);
Explanation

A practical measurement pattern for responsive components.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing UI Recipes
Focus an input on mount
Use a ref and an effect to focus an input after mount.
OpenIn sheettsxsame section
Build an interval counter
Update state on an interval with cleanup.
OpenIn sheettsxsame section
Mirror a prop into state only when necessary
Initialize from props, then manage locally.
OpenIn sheettsxsame section
Polling with effect cleanup
Periodically refresh data until unmount.
OpenIn sheettsx2 tag match
Optimistic UI with transition
Apply urgent optimistic state and schedule reconciliation.
OpenIn sheettsx2 tag match