Tech Interview RoomStudy guides

Browser & Performance

Explain reflow (layout), repaint and compositing. What is layout thrashing?

Intermediate · 2 min read · Lesson 2 of 8 in Browser & Performance

The pixel pipeline

JavaScript → Style → Layout → Paint → Composite.

  • Changing geometry (width, height, top, margin, font size, adding nodes) triggers layout, then paint and composite. Layout can affect the whole document, so it is the most expensive.
  • Changing only appearance (color, background, box-shadow) skips layout and triggers paint.
  • Changing transform and opacity on an element with its own layer needs only compositing, done on the GPU and off the main thread. That is why smooth animations use these two properties.

Layout thrashing

Reading a layout property (offsetHeight, getBoundingClientRect(), scrollTop, getComputedStyle) after writing styles forces the browser to compute layout synchronously. Doing this in a loop (write, read, write, read) forces a layout on every iteration.

Fix: batch reads, then batch writes, or schedule writes in requestAnimationFrame. Libraries like FastDOM formalise this.

Other tools

  • will-change: transform promotes an element to its own layer before an animation (use sparingly: layers cost memory).
  • content-visibility: auto skips rendering work for off-screen sections.
  • contain: layout paint limits how far a change can spread.

Example

js
// Thrashing: every iteration writes then reads, forcing layout each time
const items = document.querySelectorAll('.item');
items.forEach(el => {
  el.style.width = el.parentElement.offsetWidth / 2 + 'px';
});

// Fixed: read everything first, then write everything
const widths = [...items].map(el => el.parentElement.offsetWidth);
requestAnimationFrame(() => {
  items.forEach((el, i) => { el.style.width = widths[i] / 2 + 'px'; });
});
css
/* Animate with transform, not left/top */
.drawer { transform: translateX(-100%); transition: transform 200ms ease; }
.drawer.open { transform: translateX(0); }

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you spot these problems in DevTools?

Record in the Performance panel: purple "Layout" blocks with a red triangle and the warning "Forced reflow" point at the line that read layout after a write. The Rendering tab's "Paint flashing" and "Layer borders" show what repaints and what is composited.