liveBook · Manning

useLayoutEffect

As explained in React Quickly, Second Edition

useLayoutEffect is a React Hook that runs an effect synchronously after a component renders into the DOM but before the browser paints the update.

useLayoutEffect is a specialized effect Hook for work that must happen immediately after React updates the DOM but before the browser displays the update. It can prevent users from seeing an incorrect intermediate UI, such as a temporary 0 before a letter count appears. section 6.1.6

Preventing a visible intermediate value

Replace useEffect with useLayoutEffect when an effect updates state and the first rendered value would otherwise briefly appear on screen. The layout effect runs immediately, React applies the resulting state update, and the browser displays the corrected UI first. Keep useEffect as the default; useLayoutEffect is for specialized timing-sensitive cases. section 6.1.6

Treat useLayoutEffect as useEffect with different timing:

  • Pass an effect function and a dependency array. section 6.1.6
  • When a dependency changes, run the previous cleanup, then run the new effect. section 6.1.6
  • Use it only when asynchronous useEffect timing produces a visible or otherwise incorrect result. section 6.1.6
Figure 6.13 The timing of useLayoutEffect versus useEffect. Note how the layout effect is run just after the DOM is updated, but before the browser has had a chance to lay out the elements using CSS. (Sorry for the crowded diagram!)
06-13

Compare the execution points of useLayoutEffect and useEffect: the layout effect runs after the DOM update but before the browser lays out elements with CSS. section 6.1.6

How React Quickly, Second Edition covers it

How deep it goes
Explains timing, dependencies, cleanup, and rerender behavior, while stopping short of broader implementation internals.
Examples
Uses a letter-count display, a temporary zero, lifecycle-method conversion, and effect-timing diagrams.
What it assumes
Assumes familiarity with component rendering, state updates, useEffect, dependency arrays, and cleanup functions.
What you can do after
Apply it via React when useEffect allows a visibly incorrect intermediate render.
How it connects
Contrasts useEffect, updates state, operates after DOM rendering, and supports cleanup functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.