FE Interview Hub
Web VitalsIntermediate

What are Reflow and Repaint? How do you optimise them?

AI Practice

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 in position
  • 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, some box-shadow changes

How to optimise

  1. Batch DOM / style changes

    • Toggle a single class instead of setting many inline styles.
    • Use display: none while mutating, then show again; or build DOM offline with DocumentFragment.
  2. 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');
    
  3. Animate with transform and opacity

    • These properties skip layout and paint, going straight to compositing on the GPU.
  4. Promote to a composite layer

    • will-change: transform or transform: translateZ(0) isolates an element so its changes don't affect others.
  5. Avoid table-based layouts

    • A change in any cell can reflow the entire table.
  6. Use requestAnimationFrame for scroll / animation work

    • Schedules visual updates with the next frame, avoiding duplicate reflows in a single frame.
  7. 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