from setState to pixels

2026/04/14
frontendreactbrowserrendering

You call setState, and the screen does not change on that line. What you've done is schedule a rerender. React runs it, writes the result into the DOM, and the browser still has to turn that DOM into pixels before anything changes on screen.

Take a search box. You type "a". The input should show "a", and the result list below it should filter down. Between your keystroke and those pixels there are nine steps. React owns the first three and the last; the browser owns the five in the middle, the same work it does with or without a framework.

setState
  → render           ┐
  → commit           │  React
  → useLayoutEffect  ┘
  → Style Recalc     ┐
  → Render Tree      │
  → Layout           │  browser
  → Paint            │
  → Composite        ┘
  → useEffect           React (usually here; section IX has the exceptions)

I. The render phase

React calls your component function again. The function returns a new tree of plain JavaScript objects, often called the Virtual DOM. The browser has no idea this tree exists. It's just memory.

React compares the new tree against the previous one. Two rules govern the diff:

  • Different element type at the same spot (a <div> became a <section>)? Tear down the old subtree, build a new one.
  • List items? The key prop tells React which item is which across renders.

Since React 18, this phase can be paused and restarted. With startTransition, you mark an update as low priority. According to react.dev, if a more urgent update arrives before that render finishes, React drops the partial render, handles the urgent update, and then starts the low-priority render again. Nothing has touched the DOM yet, so throwing away the unfinished work is safe.

const [input, setInput] = useState('')
const [query, setQuery] = useState('')
 
function handleChange(e) {
  setInput(e.target.value)           // high priority. update input immediately
 
  startTransition(() => {
    setQuery(e.target.value)         // low priority. React can interrupt this render
  })
}
 
// <ExpensiveList> rerenders with query.
// If the user types again before it finishes, React drops
// the ongoing render and restarts with the latest query.

Without startTransition, an update from a keystroke renders synchronously in one go. The input lags until the list finishes.

II. The commit phase

The diff is ready: in the search box, the input's value changes to "a", and a dozen list items get removed. React writes those changes to the real DOM.

This phase cannot be interrupted. Once the DOM starts changing, stopping halfway would leave a half-updated page on screen, so React runs it to completion.

Internally, in ReactFiberCommitWork.js, commit runs three stages:

  • Before mutation: read what the DOM looks like before it changes. Class components use getSnapshotBeforeUpdate here to record things like scroll position.
  • Mutation: actual DOM writes. insertBefore, removeChild, setAttribute. Old refs are detached and the previous useLayoutEffect cleanups run here.
  • Layout: attach the new refs, fire useLayoutEffect. So "useLayoutEffect runs after commit" really means it runs inside the last of these three.

III. useLayoutEffect

Before the browser paints anything, React fires useLayoutEffect synchronously.

A tooltip shows why this matters. It should sit below its button, unless there's no room below, in which case it flips above. You can't know that until the tooltip is in the DOM and you measure its height. useLayoutEffect is the last moment to measure (getBoundingClientRect, offsetHeight, scroll position) and fix the DOM before the user sees anything. As react.dev points out, if you measure in useEffect instead and then set state to move the tooltip, the browser may already have painted it in the wrong place, and the user sees it jump.

A tooltip opened by a click jumps too. Tested on headless Chrome 156: click a button, the tooltip renders below it, useEffect measures its height and calls setState to flip it above. In both React 18.3.1 and 19.3.1, 10 of 10 runs painted a frame with the tooltip below before it moved. With useLayoutEffect, all 10 painted it above from the first frame.

After a click, useEffect itself does run before the paint (section IX measures it). So why the jump? The effect running early doesn't mean the render its setState starts also finishes before the paint. React gives updates a priority, and a click's update is the highest, so React renders it right away. In the source of both 18.3.1 and 19.3.1, an update scheduled inside an effect after a click gets DefaultEventPriority, lower than the click. React doesn't render a default-priority update right away; it hands it to its Scheduler, which runs it in a separate task. React doesn't promise that task comes before the browser's next paint, and in all 10 runs the paint came first.

Reading layout is synchronous and blocking, for every entry on the list of properties that force layout: getBoundingClientRect() computes style and layout on that line, no Promise, no await to warn you. A read forces that compute only when layout is dirty, and a write dirties it. One read is one pass:

read → style recalc → layout

Interleave writes and each one re-dirties, so the pass runs again and again (layout thrashing):

read → style recalc → layout → write → style recalc → layout → write → style recalc → layout

Fix: batch all reads, then all writes. For pure measurement, ResizeObserver / IntersectionObserver report asynchronously, no forced layout.

Commit just wrote to the DOM, so layout is dirty when useLayoutEffect starts. The first read inside it runs Style Recalc, Render Tree and Layout right there, before the call returns. In that case sections IV to VI happen early, inside the effect, and the browser reuses the result unless the effect writes again. A trace recorded on headless Chrome 156, writing to the DOM and then calling getBoundingClientRect() once, shows 16 nested events between the call and its return, the same 16 in each of three runs. Among them, in order, are Document::recalcStyle, Document::rebuildLayoutTree and Layout, one for each of those sections; the rest are wrappers such as Document::UpdateStyleAndLayout and finer steps inside them.

useLayoutEffect blocks the paint. Keep it fast.

Now the browser takes over.

CRP, technically. People call this whole pipeline (Style Recalc through Composite) the Critical Rendering Path. Strictly, by web.dev's definition, CRP is the path to the first render of a page. After that, setState reuses the same steps, but it isn't CRP anymore: CRP is about which resources (HTML, CSS, parser-blocking scripts) the first render has to wait for.

IV. Style Recalc

The DOM changed, so the browser has to work out what every affected element should look like. In the terms of CSS Cascade 5 §4, one property value on one element moves through six stages before it reaches the screen:

declared → cascaded → specified → computed → used → actual

Style Recalc runs the first four (the steps below). Used and actual finish later, in Layout and Paint.

Collecting. The browser gathers styles from three sources: its own builtin defaults (User Agent), any preferences the user has configured in their browser, and your stylesheet (Author).

Cascading. All collected declarations compete. The browser resolves conflicts in the order CSS Cascade 5 §6.1 gives, highest priority first:

  1. Transitions
  2. User Agent + !important
  3. User + !important
  4. Author + !important
  5. Animations
  6. Author
  7. User
  8. User Agent

Within the same origin and importance, the style attribute beats any stylesheet rule. Next come cascade layers (@layer); after that, specificity: IDs beat classes, classes beat type selectors. If specificity is equal, the declaration that appears last wins. The reference below gives example selectors and their scores. It puts the style attribute and !important on the same scale, as 1-0-0-0 and 1-0-0-0-0; that is a memory aid, since in the spec neither is part of specificity.

Defaulting. Properties with no declared value still need one. Two ways to fill it:
Text-ish properties inherit from the parent: color, font-size, font-family.
Box-ish properties fall back to a spec default: border-style → none, margin → 0.
Override either path with inherit, initial, unset, or revert.

Resolving (the easy half). First of two passes (section VI is the other). Anything that doesn't need geometry becomes concrete. em resolves against the element's own font size (padding: 1em on a 20px element is 20px); only inside font-size itself does it use the parent's. rem resolves against the root, bold becomes 700, relative paths become absolute URLs. Anything that needs the box size (50%, auto, min-content) can't resolve yet, so it waits for Layout.

Output: every node's computed style. Note computed: width: 50% is still 50% here, not a pixel. You can see this from JavaScript: on an element with display: none (no box, no layout), getComputedStyle(el).width returns 50%. Show the element and the same call returns 400px, because for laid-out elements it reports the value after Layout.

V. Render Tree

DOM plus computed styles merge into the Render Tree (Chrome calls it the layout tree). It's the DOM with style attached, minus the nodes that take up no space, plus a few that aren't in the DOM at all.

display: none: excluded. No node in the tree, no space in the layout.
visibility: hidden: included. Space reserved, pixels not drawn.
<title>, <head>, <script>: excluded, because the browser's default stylesheet gives them display: none.
::before / ::after with content: included. Inside look, part 3 notes they go into the layout tree even though they're not DOM nodes.

VI. Layout / Reflow

The browser walks the Render Tree and calculates the geometry of every element: position, width, height. This step is also called Reflow. In the search box, the list just lost a dozen items, so its height shrinks and everything below it moves up. Two CSS steps finish here:

Formatting. The browser organizes elements into formatting contexts: block, inline, flex, grid. Each context has rules for how its children stack and flow.

Resolving (the layout half). The second pass. 50%, auto, min-content needed a box to measure against; now it exists, so they resolve. Style Recalc gave the computed value (50%); Layout makes it the used value (400px inside an 800px parent).

Layout is expensive. Inserting a DOM node triggers it. Changing font-size triggers it. Resizing the window triggers it. Reading getBoundingClientRect mid-animation can trigger it repeatedly.

That's why useLayoutEffect sits where it does, back in section III: right after the DOM write and before the paint. Any reads there force one layout, and any correction you make lands before the user sees the first frame.

VII. Paint

Paint doesn't fill pixels yet. As Inside look, part 3 describes it, in Chrome the main thread walks the layout tree and writes down drawing instructions, called paint records: "background first, then text, then border". Raster threads later turn those records into pixels, tile by tile.

The browser splits the page into a few layers, images drawn separately and stacked at the end. Most elements share a layer with the elements around them, and an element's background, color, box-shadow and border are all drawn into that shared layer. Only a few elements get a layer of their own, for example one with will-change: transform.

Used → actual. The last of the six value stages. Some used values can't be drawn exactly. The example in CSS Cascade 5 §4.6: a device may only draw borders in whole pixels, so the browser approximates a fractional border width. (Unrelated to CSS transform: translate(), which lives in the next section.)

Paint records are made on the main thread, the same thread that runs your JavaScript.

VIII. Composite

The compositor thread takes the layers, places them, and sends a frame to the GPU, which draws it on screen.

transform and opacity live here. Measured three times on headless Chrome 156, recording a one-second trace each time: a CSS animation that only changes transform triggered no style recalc, no layout and no paint on the main thread. The same animation on left or width ran layout and paint once in every frame, about 60 times in that second (57 to 61). Moving an element by setting transform from JavaScript every frame still ran style recalc each frame, but no layout or paint.

So CSS animations on transform or opacity keep moving while the main thread is busy: per Inside look, part 3, the compositor thread doesn't wait on JavaScript or style calculation. Animations on left, top, or width need layout and paint on the main thread every frame. When JavaScript keeps that thread busy, frames are dropped and the animation stutters.

IX. useEffect

useEffect usually fires after the browser has painted. React's docs say "generally", and the exceptions matter:

  • Click, keydown, and other discrete input. The React 18 upgrade guide says React 18 and later run useEffect before the paint. On headless Chrome 156, after a click, both React 18.3.1 and 19.3.1 ran useEffect before that frame's paint. That is the effect function itself. A render started by a setState inside it landed after the paint in all 10 runs of the tooltip test in section III.
  • Anything else: a timer, a network response. React generally lets the browser paint first, but doesn't promise it. Also on Chrome 156, a setTimeout update ran useEffect after the paint in React 19.3.1, and before the next frame in React 18.3.1 (3 of 3 runs).
  • A state update inside useLayoutEffect. According to react.dev, React then runs all pending effects immediately, useEffect included.

So useEffect can run before or after paint, and even when it runs before, a setState inside it may not make this paint. It is for work that can happen a little earlier or later without mattering: data fetches, subscriptions, event listeners. In the search box, that's the request for results from the server. Work that must happen before paint goes in useLayoutEffect. As react.dev notes, work that must wait until after paint, such as an alert(), needs a setTimeout.

Say the search box has a Clear button that empties the results and then shows an alert saying they were cleared. That update comes from a click, so the useEffect may run before paint. Call alert() directly there and the dialog can appear while the old list is still on screen. And because alert blocks the main thread, the list doesn't disappear until the user presses OK:

function handleClear() {
  setResults([]);
  setCleared(true);
}
 
useEffect(() => {
  if (!cleared) return;
  // alert('Cleared'); // may show before the list disappears
  const id = setTimeout(() => alert('Cleared'), 0);
  return () => clearTimeout(id);
}, [cleared]);

setTimeout moves the alert to a later task, and the browser usually finishes painting the current frame before running it.

The naming collision

"Render" means two different things in frontend, and conflating them causes confusion in every performance discussion.

TermWhat it means
React render phaseRuns the component function, produces a Virtual DOM. The browser is not involved.
Browser Render TreeDOM + CSSOM merged. Built from the real DOM React wrote in the commit phase.

React's render phase produces JavaScript objects. The browser's Render Tree is built from real DOM nodes. They don't overlap. For a given update, React finishes render and commit before the browser builds a Render Tree from the new DOM. A transition render can pause midway, and the browser keeps showing frames of the old DOM in the meantime.

The full sequence

Does a slow stylesheet delay React's start too? If the React bundle loads with defer or type="module", yes: if the CSS arrives 1.5 s late, React starts running 1.5 s late. With async, no: the script runs as soon as it downloads, without waiting for the CSS. The index.html from Vite 7.3.7's vite build uses type="module"; this site's pages, built with the Next.js 15.5.12 App Router, use async.

To check this on headless Chrome 156, the server held the stylesheet back for 1.5 s but returned the script file right away, and the page recorded when the script started running and when the first frame (first contentful paint) was drawn. The script was downloaded early, so if it still ran only at 1.5 s, it was waiting for the CSS. Three runs per page, plus three more for defer and type="module" with the script moved before the <link>:

Script on the pageScript runs atDOMContentLoadedFirst frame
none—6 to 8 ms1528 to 1536 ms
defer1511 to 1522 mssame time as the script1520 to 1532 ms
type="module"1508 to 1516 mssame time as the script1516 to 1528 ms
async8 to 11 ms6 to 9 ms1520 to 1532 ms

For defer and type="module", it made no difference whether the script tag came before or after the <link>. Per the HTML spec's "The end" section, once parsing ends, a deferred script waits while any stylesheet the parser has seen is still loading, including one written after the script. An async script isn't part of that step, so it doesn't wait.

async only lets React's code start earlier, though. The script ran at 8 to 11 ms, but the browser doesn't paint while the stylesheet is missing. The last column is measured: with async, the first frame still appeared only at 1520 to 1532 ms, about the same as with defer.

Browser receives HTML
  │
  ├── HTML parser ──► DOM
  │                    │
  │                    ├──► React bundle runs            ← defer / module: waits for every stylesheet in the page
  │                    │                                    async: runs once downloaded, no wait for CSS
  │                    │       → createRoot(#root).render(<App />)
  │                    │       → render + commit        React writes DOM nodes (the app is live from here)
  │                    ├──► DOMContentLoaded             ← DOM parsed + defer/module scripts done
  │                    │
  └── CSS fetch ──► CSSOM
                       │
      DOM + CSSOM ─────┴──► Render Tree ──► Layout ──► Paint ──► Composite ──► First Contentful Paint
                            ↑ only once the CSS is in, even if an async React already rendered

  scripts   <script>               blocks the parser; waits for earlier stylesheets, then runs
            <script defer>         parallel fetch; runs after parsing, once every stylesheet is in
            <script async>         parallel fetch; runs as soon as it downloads
            <script type="module"> deferred like defer, with its own scope

window.onload      ← images, fonts, iframes all loaded; the app is usually running well before this

──────────────── every update after that ────────────────────────

any setState (event handler, fetch, timer, WebSocket...)
  → setState called
      ┌──────────────────────────────────────────────────┐
      │  render phase     VDOM diff; only transitions    │
      │                   can be interrupted             │
      │  commit phase     writes to real DOM             │
      │  useLayoutEffect  read layout, blocks paint      │
      │  Style Recalc     cascade, specificity, compute  │
      │  Render Tree      DOM + computed styles merged   │
      │  Layout / Reflow  geometry: position, size       │
      │  Paint            paint records per layer        │
      │  Composite        layers → GPU → screen          │
      │  useEffect        side effects (before paint     │
      │                   after a click)                 │
      └────────────────────────┬─────────────────────────┘
                               │ any setState
                               └──► back to render phase

The three paint metrics. The bootstrap path above ends at FCP (First Contentful Paint), the first text or image pixels from the DOM. Two cousins sit near it: FP (First Paint), as Paint Timing defines it, is the first pixels of anything, a non-default background counts; LCP (Largest Contentful Paint), per web.dev, is when the largest image, text block or video in the viewport renders. If that largest element is an image, LCP has to wait until the image downloads.

The loop runs for as long as the app is alive. To see how those nine steps spread across processes and threads in real time, here is the same loop laid out as a timeline:

References

React internals

  • Inside React's FiberWorkLoop. Follow up post of mine. Zooms inside the "render phase" and "commit phase" bullets above, walking through the four numbered stages of React's internal reconciler workloop.
  • React 技术揭秘 by 卡颂 (KaSong). A simplified Chinese deep dive into Fiber, Scheduler, Lanes, and Hooks. The standard narrative reference for React at source level. Source on GitHub: BetaSu/just-react.
  • 图解React: reconciler 运作流程. Another simplified Chinese resource, but function by function. Traces the reconciler in four steps from scheduleUpdateOnFiber to commitRoot, with a diagram of the call graph. Complements KaSong's book with a more concrete workflow.
  • A Cartoon Intro to Fiber by Lin Clark, React Conf 2017. Visual walkthrough of why Fiber replaced the old stack reconciler.

Browser rendering pipeline

Critical Rendering Path

Layout and reflow

  • On Layout & Web Performance by Kelly Norton. The classic post on layout thrashing. Browsers compute layout lazily, so read-write-read forces reflow every time.
  • Avoid large, complex layouts and layout thrashing by Jeremy Wagner, Paul Lewis, Barry Pollard. Concrete techniques: batch reads before writes, avoid forced synchronous layout, keep the DOM small.
  • What is DOM reflow? Stack Overflow thread. Short canonical answer for what reflow is and what triggers it.
  • Browser Rendering Optimization by Vasanth Krishnamoorthy. Notes from Paul Lewis and Cameron Pittman's Udacity course on hitting 60fps. Covers pipeline stages, frame budget, and per step optimizations.

Extensibility

  • Houdini APIs on MDN. Houdini opens the CSS engine's internal steps to userland. The Paint, Layout, and Animation Worklets would each hook into one step of the pipeline above, but only the Paint Worklet has shipped, in Chrome and Edge. Other Houdini parts, such as @property, work in Firefox and Safari too.
  • Web Workers vs Service Workers vs Worklets by Ire Aderinokun. Short comparison of what each one does; of the three, Worklets are the ones that hook into the rendering pipeline.