# Autopsy #03: Why One Click Triggers 14 Re-Renders and a Layout Shift

- **Canonical URL:** https://frontend.rocks/autopsies/fourteen-rerenders-one-click/
- **Case:** #03
- **Failure Mode:** Main-Thread Freeze
- **Production Symptom:** A single filter click freezes the UI for 180 ms INP and triggers a visible 0.14 CLS jump in the data grid.
- **Last Verified:** 2026-11-16

## Causal Chain
1. [CSS Custom Properties & Cascade](https://frontend.rocks/concepts/css-custom-properties-cascade.md): Mutating a CSS custom property on :root invalidates style resolution across all 2,400 descendant DOM nodes.
2. [Virtual DOM & Reconciliation](https://frontend.rocks/concepts/virtual-dom-reconciliation.md): Unstable inline context objects and unkeyed wrappers force 14 cascading React subtree reconciliations.
3. [Layout Thrashing (Forced Synchronous Layout)](https://frontend.rocks/concepts/layout-thrashing.md): Interleaved getBoundingClientRect() reads and style.minHeight writes force 14 synchronous Blink layouts.
4. [Long Tasks and Interaction to Next Paint (INP)](https://frontend.rocks/concepts/long-tasks-and-inp.md): Combined style, VDOM diff, and forced layouts form a 180 ms Long Task that blocks next-frame paint.
5. [Priority Lanes & Time-Slicing Schedulers](https://frontend.rocks/concepts/concurrent-rendering-lanes.md): Running heavy grid filtering on the synchronous SyncLane prevents React from yielding to input paint.

## Primary Sources
- https://drafts.csswg.org/css-variables/#defining-variables
- https://web.dev/articles/inp
- https://web.dev/articles/avoid-large-complex-layouts-and-layout-thrashing
- https://react.dev/reference/react/startTransition

---
## Incident Report

A design-system polish PR added a compact-density toggle to the catalog filter bar, updating `--row-density` on `:root` and equalizing row heights in `useLayoutEffect`. On an M3 MacBook Pro with 20 test items, the toggle felt instantaneous.

On production catalog pages with 2,400 DOM nodes, Core Web Vitals telemetry flagged an immediate Interaction to Next Paint (INP) and Cumulative Layout Shift (CLS) regression.

- **T+00:00**: Filter density feature ships to 100% of catalog traffic.
- **T+15:00**: RUM p75 INP jumps from 38 ms to 180 ms on mid-tier Android devices.
- **T+25:00**: CLS spikes to 0.14 as the sticky toolbar drops 24 px downward on every filter click.
- **T+40:00**: DevTools Performance traces capture a 180 ms Long Task containing 14 React commit phases and 14 purple `Layout` bars per click.

## The Red Herring

In Slack, the team immediately wrapped `<CatalogGrid>` in `React.memo` and pushed a hotfix. Local unit tests confirmed `<CatalogGrid>` skipped renders when unrelated props stayed equal.

In production, `React.memo` saved zero milliseconds. Every click mutated a root CSS variable, recreated the parent context `value={{ filter, density }}` object literal, and interleaved `getBoundingClientRect()` reads with `style.minHeight` writes inside `useLayoutEffect`.

## Causal Chain

One click cascades through five rendering layers. A `:root` custom property invalidates 2,400 style nodes, unstable context values trigger 14 synchronous VDOM reconciliations, `useLayoutEffect` interleaves reads and writes into 14 forced layouts, the combined work creates a 180 ms Long Task, and synchronous lane scheduling blocks the browser from painting the clicked chip.

## Failure Simulator

Toggle between the broken synchronous architecture and the concurrent, batched implementation below to compare style invalidation scope, forced layout counts, and resulting INP latency.

## Layer Dissection

### 01 → 02: Root CSS Variable Mutation Triggers Cascade and Re-Render Storm

Mutating `--row-density` on `document.documentElement` (`:root`) forces Blink to re-evaluate inherited [CSS Custom Properties & Cascade](/concepts/css-custom-properties-cascade) across all 2,400 descendant nodes.

Simultaneously, the click handler updates a top-level provider whose `value={{ filter, density }}` literal allocates a fresh object reference. Under [Virtual DOM & Reconciliation](/concepts/virtual-dom-reconciliation), every consumer subtree fails `Object.is` equality and schedules 14 cascading re-renders.

### 02 → 03: Commit Effects Interleave Reads and Writes Into Layout Thrashing

During the synchronous commit phase of those 14 re-renders, `useLayoutEffect` loops over visible rows to equalize heights:

- **Read**: `el.getBoundingClientRect().height` forces Blink to flush pending `:root` style invalidations and compute geometry immediately.
- **Write**: `el.style.minHeight = ...` marks the box tree dirty again for the next iteration.

Repeating this read-write pair 14 times triggers [Layout Thrashing (Forced Synchronous Layout)](/concepts/layout-thrashing) and shifts the sticky header before paint.

### 03 → 04: Forced Layouts Inflate the Interaction Into a 180 ms Long Task

Because `useLayoutEffect` executes synchronously before Blink composites the next frame, 2,400 style recalculations, 14 VDOM diffs, and 14 forced layouts execute inside one macrotask. Under [Long Tasks and Interaction to Next Paint (INP)](/concepts/long-tasks-and-inp), any task exceeding 50 ms starves the renderer; at 180 ms, the active chip remains unpressed for 11 frames.

### 04 → 05: SyncLane Prevents Yielding Between Urgent Chip Paint and Grid Work

Calling `setFilter(next)` directly schedules the 500-row grid filter on React's [Priority Lanes & Time-Slicing Schedulers](/concepts/concurrent-rendering-lanes) (`SyncLane`).

- **Synchronous lane**: Blocks Blink from painting the pressed chip until all 500 rows reconcile.
- **Transition lane**: Wrapping `setFilter(next)` in `startTransition` yields between chunks so the chip paints in under 16 ms.

## Architectural Fix & Invariants

```tsx
function FilterBar({ gridRef, rowsRef, setUrgentChip, setGridFilter }: Props) {
  const handleSelect = (next: FilterState) => {
    setUrgentChip(next.id); // SyncLane: paints pressed chip in < 16 ms
    gridRef.current?.style.setProperty('--row-density', next.density);

    startTransition(() => {
      setGridFilter(next); // TransitionLane: yieldable 500-row reconciliation
    });

    requestAnimationFrame(() => {
      const heights = rowsRef.current.map((el) => el.getBoundingClientRect().height);
      rowsRef.current.forEach((el, i) => {
        el.style.minHeight = `${heights[i] + 4}px`;
      });
    });
  };
  return <ChipGroup onSelect={handleSelect} />;
}
```

**Architectural Invariants:**
- **Scoped custom properties**: Write dynamic CSS variables to the nearest container (`gridRef.current`) with `contain: layout style`, never `:root`.
- **Two-lane input split**: Keep immediate visual feedback (`setUrgentChip`) on `SyncLane` and wrap expensive list filtering in `startTransition`.
- **Strict read-then-write batching**: Complete all `getBoundingClientRect()` reads in one pass before executing any `style` mutations.
- **INP budget gate**: Fail performance CI on any interaction trace whose total `Presentation Delay` exceeds 100 ms or triggers more than 1 `Layout` event per frame.

**Golden Rule:** Keep urgent feedback on `SyncLane`, push heavy list reconciliation to `TransitionLane`, and never interleave DOM geometry reads with style writes.
