CodeBlanks Logo Icon CodeBlanks

Measuring

Learn to measure an element's size via a ref.

Measuring

With useRef you can access DOM nodes and measure them. You attach a ref attribute to capture the node, then read dimensions like ref.current.offsetWidth.

Measurement is usually done inside useEffect; after render the DOM is ready. Writing the result to state re-renders the component and shows the measurement.

Measurement is expensive; do it only when needed, not on every render. Using ResizeObserver to track size changes is common.

useLayoutEffect vs useEffect

For measurement there are two options: useEffect and useLayoutEffect. useLayoutEffect runs synchronously before paint; this avoids layout jump.

useEffect runs asynchronously after render; the browser paints first, then measurement happens. A brief flicker may be visible.

If you change styles based on measurement, prefer useLayoutEffect; if you only read data, useEffect is enough.

Practice Width measurement

Complete the skeleton below. Write a MeasureBox component; get boxRef with useRef(null), read boxRef.current.offsetWidth inside useEffect and write to state with setWidth, render <div ref={boxRef}>. Export it.

Starter code

App.jsx
import { useRef, useEffect, useState } from "react";

// Write the MeasureBox component here

Sample solution

App.jsx
import { useRef, useEffect, useState } from "react";

function MeasureBox() {
  const boxRef = useRef(null);
  const [width, setWidth] = useState(0);
  useEffect(() => {
    if (boxRef.current) setWidth(boxRef.current.offsetWidth);
  }, []);
  return <div ref={boxRef}>Width: {width}px</div>;
}

export default MeasureBox;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which hook is measurement done in?

  • useMemo
  • useState
  • useEffect Correct answer
  • useCallback

Explanation: Measurement is done in useEffect; the DOM is ready.

2 Reading offsetWidth

Question
useEffect(() => {
  if (boxRef.current) {
    setWidth(boxRef.current.____);
  }
}, []);
Answer
useEffect(() => {
  if (boxRef.current) {
    setWidth(boxRef.current.offsetWidth);
  }
}, []);

Explanation: offsetWidth gives the element's width in pixels.

3 Measuring: match the terms

Term Meaning
useRef DOM node
offsetWidth Width measurement
useEffect After paint
useLayoutEffect Before paint

All lessons in Intermediate