0Pricing
React Academy · Lesson

Measuring DOM Elements with useLayoutEffect

Read element dimensions, positions, and scroll offsets after layout but before paint to avoid flickering.

getBoundingClientRect Overview

element.getBoundingClientRect() returns a DOMRect object with the element's size and position relative to the viewport: top, right, bottom, left, width, and height. It forces the browser to perform a layout calculation to return accurate values, so call it sparingly.

The Problem with Reading in useEffect

If you read getBoundingClientRect() in a useEffect, the browser has already painted. If you then set state based on the measurement, React re-renders and the browser paints again. Users may see the element briefly in its wrong position or size before the correction appears in the second paint.

All lessons in this course

  1. The Rendering Phase and DOM Commit
  2. When useLayoutEffect Runs vs useEffect
  3. Measuring DOM Elements with useLayoutEffect
  4. Avoiding Layout Thrash and Visual Flicker
← Back to React Academy