Web VitalsIntermediate
What are Reflow and Repaint? How do you optimise them?
What are Reflow and Repaint?
A simplified browser rendering pipeline:
JS → Style → Layout (Reflow) → Paint (Repaint) → Composite
- Reflow (a.k.a. layout): triggered when an element's geometric properties change (size, position, or DOM structure). The browser must recompute the layout tree and then repaint.
- Repaint: triggered when an element's visual properties change (e.g. color, background, visibility) without affecting layout. Only painting is needed — no layout.
A reflow always implies a repaint. A repaint does not necessarily imply a reflow. Reflow is significantly more expensive than repaint.
What triggers a Reflow?
- Adding or removing DOM nodes
- Changing size:
width,height,padding,margin,border - Changing position:
top,left, changes inposition - Changing font size or line height
- Window resize, web font loading
- Reading properties that force a synchronous layout:
offsetWidth,offsetHeight,clientTop,scrollTop,getBoundingClientRect(),getComputedStyle()
What triggers only a Repaint?
color,background-color,visibility,outline, somebox-shadowchanges
How to optimise
Batch DOM / style changes
- Toggle a single
classinstead of setting many inline styles. - Use
display: nonewhile mutating, then show again; or build DOM offline withDocumentFragment.
- Toggle a single
Avoid layout thrashing (forced synchronous layout)
- Don't interleave reads and writes inside a loop. Read first, then write.
// Bad: every iteration forces a reflow for (const el of items) { el.style.width = el.offsetWidth + 10 + 'px'; } // Good: read first, then write const widths = items.map(el => el.offsetWidth); items.forEach((el, i) => el.style.width = widths[i] + 10 + 'px');Animate with
transformandopacity- These properties skip layout and paint, going straight to compositing on the GPU.
Promote to a composite layer
will-change: transformortransform: translateZ(0)isolates an element so its changes don't affect others.
Avoid table-based layouts
- A change in any cell can reflow the entire table.
Use
requestAnimationFramefor scroll / animation work- Schedules visual updates with the next frame, avoiding duplicate reflows in a single frame.
Leverage the Virtual DOM
- Frameworks like React / Vue diff and batch DOM mutations for you.
Summary
| Type | Trigger | Cost |
|---|---|---|
| Reflow | Geometric change | High (re-layout) |
| Repaint | Visual change | Medium |
| Composite | transform / opacity | Low (GPU) |
Key idea: reduce reflows, animate with transform/opacity, and never force synchronous layout.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
