---
name: fix-ui-lag
description: Profile your web app at 4x CPU throttle in Chromium and fix the drag lag, click freezes, scroll stutter, and idle battery drain you never feel on an M-series Mac: React setState on pointermove/scroll, animating width/left/clip-path, html overflow:hidden modal freezes, CSS variables mutated on root per move, layout thrashing in rAF loops, missing will-change on dragged layers, and off-screen infinite animations.
license: MIT
metadata:
  author: Hairline UI
  url: https://hairlineui.com/skills/fix-ui-lag
  version: "1.0.0"
---

# /fix-ui-lag

Profile your app at **4× CPU throttle** (simulating a mid-range phone or busy laptop) and fix the hidden main-thread freezes, trailing drags, scroll stutters, and idle battery leaks you never notice on a fast dev machine.

This skill is **zero-redesign and zero-lock-in**. It does not change how your UI looks — it fixes *how* interactions move and render, and verifies the improvement with real Chrome DevTools Protocol (CDP) numbers.

## Guardrails (never break these)

- **Measure first, optimize second.** Run the 4× CPU profiler before editing code so you fix real bottlenecks instead of sprinkling random `React.memo` everywhere.
- **Never slap `will-change: transform` permanently on dozens of static elements.** Promoting too many layers explodes GPU memory and blurs scaled text. Apply `will-change: transform` only to actively dragged/moving surfaces (or toggle it during drag/zoom and clear it on settle).
- **Preserve exact UX, keyboard accessibility, and reduced-motion behavior.**
- **Never add external libraries.** Every fix uses standard React, DOM, and CSS primitives.
- **Verify at 4× CPU after every fix** and report real before/after numbers.

---

## Step 1 — Measure the baseline at 4× CPU

### 1A. Run the Chromium 4× CPU profiler (recommended)

With your local dev server (or production build — **production builds give the truest React numbers!**) running, fetch and run the verifier:

```bash
curl -sL https://hairlineui.com/skills/fix-ui-lag-check.mjs -o /tmp/fix-ui-lag-check.mjs
node /tmp/fix-ui-lag-check.mjs http://localhost:3000 --routes /,/board
```

Optional targeted flags when testing a specific draggable card, slider, or modal button:

```bash
node /tmp/fix-ui-lag-check.mjs http://localhost:3000/board --drag "[data-card]" --click "button[aria-haspopup]"
```

Record the baseline numbers:
- **Worst click/modal long task (ms)** and whether `<html>` / `<body>` `overflow` mutated
- **Scroll p95 frame time (ms)**, layout count, and whether root CSS variables mutated
- **Drag/sweep p95 frame time (ms)**, layouts/sec, and recalc-styles/sec
- **Idle off-screen infinite animations** and idle `rAF` tick rate

### 1B. Static source scan for known lag patterns

```bash
G='-g *.{tsx,jsx,ts,js,vue,svelte} -g !node_modules -g !.next -g !dist'

# 1. Modal/drawer scroll lock mutating <html> or <body> overflow (causes 300-850ms full-page restyle stalls)
rg -n '(documentElement|body)\.style\.(overflow|scrollbarGutter|paddingRight)\s*=' $G .

# 2. Setting CSS variables on <html> or document.body inside listeners/loops (restyles entire DOM per frame)
rg -n '(documentElement|body)\.style\.setProperty\(' $G .

# 3. Blanket transition-all or animating layout properties
rg -n '\btransition-all\b|transition:\s*all\b' $G .
rg -n 'transition-\[[^\]]*\b(width|height|top|left|right|bottom|margin|padding|clip-path)\b' $G .

# 4. High-frequency pointer/scroll handlers calling React setState directly
rg -n '(onPointerMove|onMouseMove|onTouchMove|onScroll|pointermove|mousemove|scroll)' $G .

# 5. Layout reads inside requestAnimationFrame or move handlers
rg -n 'getBoundingClientRect|offsetTop|offsetLeft|offsetWidth|offsetHeight|scrollHeight|getPointAtLength' $G .

# 6. Infinite animations (check if paused off-screen / under prefers-reduced-motion)
rg -n 'animate-(spin|pulse|bounce|ping)|animation-iteration-count:\s*infinite|iterations:\s*Infinity' $G .
```

---

## Step 2 — Fix the real bottlenecks

### 2.1 Dragging, sliders, resizable panes, and hover sweeps trailing behind the pointer

Why drags lag at 4× CPU: React re-renders every pixel of movement, CSS mutates `left`/`top`/`width`/`height` (forcing layout + full repaint), or the element is not on its own compositor layer (300ms+ of raster per second).

- **Write transforms directly to DOM refs during the gesture — zero React `setState` per pointer move:**
  ```tsx
  // Bad: re-renders the whole subtree 60-120 times per second
  const onPointerMove = (e: React.PointerEvent) => setPos({ x: e.clientX, y: e.clientY });

  // Good: mutate transform on the element ref directly; commit React state on pointerup
  const onPointerMove = (e: React.PointerEvent) => {
    const dx = e.clientX - dragRef.current.startX;
    const dy = e.clientY - dragRef.current.startY;
    dragRef.current.dx = dx;
    dragRef.current.dy = dy;
    cardRef.current!.style.transform = `translate3d(${dx}px, ${dy}px, 0)`;
  };
  ```
- **Promote the dragged layer while moving:** set `will-change: transform` on pickup (or on an actively dragged card/thumb), and clear it when settled if the element scales/zooms so text re-rasterizes crisply.
- **Never read layout inside the frame loop:** read `getBoundingClientRect()` / `offsetLeft` / `offsetTop` **once at `pointerdown`** and track deltas from pointer coordinates during `pointermove`. Reading geometry after writing styles forces synchronous layout thrashing every frame.
- **Use `transform` instead of `left`/`top`/`width`/`height`/`clip-path`:**
  - Dragging/sorting → `translate3d(x, y, 0)`
  - Magnifying/resizing thumbs → `scale(...)` + `translate3d(...)` from fixed rest positions
  - Image/wipe reveals → two counter-moving composited layers (`translateX`) instead of animating `clip-path` per frame (animating `clip-path` re-rasterizes the full image every frame).
- **Highlights fade via `opacity`, not repainted borders/backgrounds:** when dragging a card over a drop column, toggle an overlay's `opacity` instead of changing the column's border and background color (cuts raster time in half).

### 2.2 Modal / drawer open freeze (`html { overflow: hidden }`)

Toggling `document.documentElement.style.overflow = 'hidden'` or `scrollbar-gutter` on `<html>` forces Chrome to restyle and relayout the **entire document** on the exact frame the user clicks — commonly blocking the main thread for `300ms–850ms` on real pages at 4× CPU.

- **Fix:** Leave `<html>` untouched (`scrollbar-gutter: stable` declared once statically in CSS). Prevent background scroll by:
  1. Adding `overscroll-behavior: contain` on the scrollable dialog/drawer panel, and
  2. Intercepting `wheel` and `touchmove` on the backdrop/overlay (with `{ passive: false }`), allowing scroll only inside the scrollable dialog content when it can scroll in that direction.

### 2.3 Root CSS custom properties mutated on scroll or pointer move

Setting `document.documentElement.style.setProperty('--scroll-y', ...)` or `--mouse-x` on a top-level wrapper invalidates style inheritance for **every descendant node in the page** on every frame.

- **Fix:** Write `transform` directly to the 1–3 elements that actually move, or scope `--p` strictly to the **smallest local container** (a single card or section with minimal children) — never `<html>`, `<body>`, or `<main>`.

### 2.4 Scroll stutter & wheel-step jank

- **One read, one write per frame:** attach `{ passive: true }` to `scroll` and `wheel` listeners, record the target scroll value, and apply DOM writes in a single `requestAnimationFrame` callback that **stops scheduling itself once settled** (sleeping loop).
- **Throttle React commits:** if React state truly needs scroll/scrub data (e.g. an active heading pill), commit only when the discrete index changes — never raw pixel offsets at 60Hz (aim for `<= 10` state updates/sec).
- **Replace `transition-all`:** name only composited properties (`transition-[transform,opacity]` or `transition-colors`). `transition-all` inspects every property on style recalc and accidentally animates layout properties on resize.

### 2.5 Idle battery & CPU drain (off-screen and hidden-tab loops)

Spinners, shimmer skeletons, marquee strips, Canvas/WebGL loops, and `requestAnimationFrame` clocks keep burning CPU/GPU even when scrolled off-screen or when the browser tab is in the background.

- **Gate every loop with `IntersectionObserver` + `document.hidden` (`visibilitychange`):**
  ```ts
  // Pause rAF, Canvas, WebGL, and timers whenever off-screen OR tab hidden
  const active = isIntersecting && !document.hidden && !reducedMotion;
  ```
- **Pause CSS infinite animations when off-screen or hidden:** toggle `animation-play-state: paused` (or only apply `animate-spin` while `status === 'pending'`, never on a hidden spinner).
- **Respect `prefers-reduced-motion: reduce`:** pause or disable continuous loops immediately when reduced motion is enabled.
- **Avoid unnecessary DOM bloat in animated lists/counters:** memoize list rows on primitive values, store event callbacks in a ref so one row changing doesn't re-render 100 siblings, and check whether hidden responsive elements (`hidden md:block`) are still running measurement effects (`ResizeObserver` / `getBoundingClientRect`).

---

## Step 3 — Re-profile at 4× CPU and prove the win

1. Run your project's typecheck and production build (or restart dev server).
2. Re-run the exact same 4× CPU profiler command:
   ```bash
   node /tmp/fix-ui-lag-check.mjs http://localhost:3000 --routes /,/board --drag "[data-card]"
   ```
3. Confirm:
   - Click/modal long tasks `< 100ms` (target `< 50ms`) with `0` `<html>` overflow mutations.
   - Drag and scroll p95 frame times `<= 20ms` (~60fps) with minimal layouts/recalc styles per second.
   - `0` off-screen infinite animations or unthrottled idle `rAF` loops burning CPU.

---

## Step 4 — Report (keep it tight)

```text
/fix-ui-lag — profiled at 4× CPU throttle

  Modal open long task:           642ms → 14ms   (removed html overflow:hidden lock)
  Card drag p95 frame time:      52.4ms → 11.8ms (ref transform + will-change, 0 React renders)
  Drag layouts / recalcs:        48 / 52 → 0 / 2
  Scroll root CSS var mutations:     yes → no
  Off-screen running loops:            3 → 0     (IntersectionObserver + visibilitychange)

Files changed:
- src/components/KanbanCard.tsx — ref-driven translate3d during drag, commit on pointerup
- src/components/Dialog.tsx — replaced html overflow lock with overlay wheel/touch lock
- src/components/Marquee.tsx — paused animation off-screen and in hidden tabs

Not checked:
- WebGL chart on /analytics (tested / and /board only)
```
