Everything feels smooth on an M-series Mac and stutters on a real phone. This skill throttles Chromium to 4× CPU, measures real long tasks and layout storms during clicks, scrolls, and drags, then fixes the root cause.

42px lag
BUG-412

Fix checkout scroll

setState · left/top

Main thread · 4× CPU14 FPS
Before373 ms/s repaint · trails cursor
0px lag
BUG-412

Fix checkout scroll

ref · translate3d

Compositor · 4× CPU60 FPS
After14 ms/s · glued under pointer

Install

Copy the skill URL or pick your coding agent below. One file, no npm packages, MIT licensed.

https://hairlineui.com/skills/fix-ui-lag.md

Claude Code

Works in: Claude Code CLI, VS Code & JetBrains extensions, and Claude Desktop Code tab

Run this once inside your project (or use ~/.claude/skills for every project).

terminal
mkdir -p .claude/skills/fix-ui-lag && curl -sL https://hairlineui.com/skills/fix-ui-lag.md -o .claude/skills/fix-ui-lag/SKILL.md

Restart or type /fix-ui-lag in Claude Code. It scans the repo, runs the Chromium verifier, and reports every fix.

  • Zero redesign risk. Leaves your layout, brand colours, typography and component library alone.

  • Verified, not guessed. Every skill pairs static checks with a standalone verifier that proves the before and after counts.

  • No lock-in, MIT. Plain markdown plus a standalone script. Works on React, Next.js, Vue, Svelte, Astro or plain HTML.

What it catches

Every rule targets an objective browser defect and pairs a detection check with a root-cause fix.

  1. Dragged cards & sliders trailing behind the pointer

    Calling React setState on pointermove, animating left/top/width, or omitting will-change on dragged elements forces 300ms+ of raster per second.

    Writes translate3d directly to refs during the gesture, promotes the moving layer, reads offsets once at pickup, and commits React state on pointerup.

  2. Modal open freeze (html { overflow: hidden })

    Toggling overflow: hidden on <html> restyles and relayouts the entire document on the click frame — blocking the main thread for 300–850ms at 4× CPU.

    Keeps <html> untouched (static scrollbar-gutter: stable) and blocks background scroll on the overlay via wheel/touchmove + overscroll-behavior: contain.

  3. CSS custom properties mutated on <html> or <body>

    Writing --scroll-y or --mouse-x to documentElement on scroll or pointermove invalidates style inheritance for every node on the page every frame.

    Writes transforms directly to the few moving elements or scopes custom properties strictly to the smallest local container.

  4. Layout thrashing & blanket transition-all

    Reading getBoundingClientRect or offsetTop after style writes forces synchronous reflows, while transition-all watches layout properties on every recalc.

    Batches reads before writes in a sleeping rAF loop and restricts transitions to explicit composited properties (transform, opacity).

  5. Off-screen infinite animations & idle rAF drain

    Hidden spinners, marquees, canvases, and rAF loops keep burning CPU/battery even when scrolled out of view or in background tabs.

    Gates every animation and rAF loop with IntersectionObserver, visibilitychange, and prefers-reduced-motion.

Chromium 4× CPU profiler

Connects directly to Chrome DevTools Protocol with Emulation.setCPUThrottlingRate: 4, samples idle rAF call rates and off-screen running animations, scrolls and drags real elements while measuring p95 frame time and Layout/RecalcStyle deltas, watches <html>/<body> for overflow or CSS-variable mutations, and captures main-thread long tasks on click.

curl -sL https://hairlineui.com/skills/fix-ui-lag-check.mjs -o /tmp/fix-ui-lag-check.mjsnode /tmp/fix-ui-lag-check.mjs http://localhost:3000 --routes /,/board --drag "[data-card]"

Then just run it

Run it on a single page while building, or across your main routes before shipping.

  • “Run /fix-ui-lag at 4x CPU on /board and fix why dragging cards trails behind the cursor.”

  • “Audit our modals and drawers with /fix-ui-lag and remove any html overflow:hidden scroll lock stalls.”

  • “Profile the app with /fix-ui-lag and pause any off-screen spinners or idle requestAnimationFrame loops.”

Source

Read every line before installing. Both files are plain text under the MIT licence.

---name: fix-ui-lagdescription: 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: MITmetadata:  author: Hairline UI  url: https://hairlineui.com/skills/fix-ui-lag  version: "1.0.0"---# /fix-ui-lagProfile 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:```bashcurl -sL https://hairlineui.com/skills/fix-ui-lag-check.mjs -o /tmp/fix-ui-lag-check.mjsnode /tmp/fix-ui-lag-check.mjs http://localhost:3000 --routes /,/board```Optional targeted flags when testing a specific draggable card, slider, or modal button:```bashnode /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```bashG='-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 propertiesrg -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 directlyrg -n '(onPointerMove|onMouseMove|onTouchMove|onScroll|pointermove|mousemove|scroll)' $G .# 5. Layout reads inside requestAnimationFrame or move handlersrg -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 pointerWhy 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 moveSetting `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 win1. 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 tabsNot checked:- WebGL chart on /analytics (tested / and /board only)```
/skills/fix-ui-lag.md
The full skill in plain markdown with YAML frontmatter. Drop into .claude/skills, .cursor/rules or .agents/skills.
/skills/fix-ui-lag-check.mjs
Standalone Node verifier for /fix-ui-lag. Runs locally with --json and --fail flags.

Templates

Every Hairline template passes these out of the box

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.