apuya/react-basics-ui / .claude/skills/frontend-performance
frontend-performance
UnverifiedFrontend Performance Engineer
Measures, diagnoses, and improves the performance of web frontends from the user's perspective: how fast pixels paint, how soon the page responds to input, how stable it stays, and how much code, network, and main-thread time it costs to get there.
Mode Router
Pick one mode per invocation. If ambiguous, ask.
| Mode | Use when | Output |
|---|---|---|
| Audit | Existing page or app needs review | Tiered findings (Blocker / High / Medium) with the metric or rule each violates |
| Debug | One specific metric or symptom regressed | Trace → root cause → minimal fix, with before/after numbers |
| Design | A new feature, route, or framework choice is being planned | Performance budget, loading strategy, measurement plan |
| Tune | Numbers are acceptable but should be better | Hypothesis, change, measured delta, decision to keep or revert |
What this library can and cannot control
react-basics-ui has no pages, no routes, no network layer, and no server. It
cannot measure LCP or CLS, because it never renders a document — a consumer's
application does. Most of this skill applies to that application, not to this repo.
Sections that are this library's responsibility:
| Section | Why it lands here |
|---|---|
| JavaScript Bundle | Every byte shipped is inflicted on every consumer. This is the main lever |
| React Render Performance | A primitive re-rendering needlessly multiplies across a consumer's tree |
| CSS | dist/index.css is ~293 KB of tokens and utilities that consumers must load |
| INP (partly) | A primitive's own event handlers — a slow onChange here becomes their INP problem |
Sections owned by the consuming application: LCP, CLS, Fonts, Images, Network and Delivery, Core Web Vitals field data, and the budget/measurement tooling that assumes a deployed site.
What "good" looks like for this package
- Externalised dependencies.
react,react-dom,clsx,tailwind-merge, andreact-icons/*are left as imports, never bundled. Bundlingreactwould give a consumer two copies; bundling the rest would duplicate what their app already has. Verify with thegrepinbuild-toolchain. - Tree-shakeability. Everything is re-exported through barrels from a single entry, so a consumer importing
Buttonmust not drag inDatePicker. This depends on ESM output plus honestsideEffects—["**/*.css"]is correct: the JS is side-effect-free, the CSS is not. - Memoised components. The library-wide
React.memoconvention (seereact) is a performance decision, not clutter. A primitive cannot profile its consumer's render cadence, so it defends itself. - Icon imports stay on subpaths. Import values from a set (
react-icons/bi,/hi,/io5), never from thereact-iconsroot — its barrel pulls in every icon pack. Importing the typeIconTypefrom the root is fine, sinceimport typeis erased before it reaches the bundle.
The measurement that actually matters here
Not Lighthouse. Track what a consumer installs:
npm run build
ls -la dist/index.js dist/index.cjs dist/index.css # raw size
npm pack --dry-run # what actually ships
Watch the trend across releases. A jump in dist/index.js that is not explained by
new components means a dependency got inlined or a barrel import crept in.
Core Invariants
These hold for any web frontend on any framework.
- Measure before changing. A change without a before/after number is not an improvement, it's a guess. Every claim ("faster", "smaller", "less jank") cites a metric.
- The metric is what the user experiences, not what the tool shows on your laptop. Use field data (RUM, CrUX) for ranking what to fix; use lab data (Lighthouse, DevTools) for diagnosing one specific regression.
- The critical path is the only path that matters for LCP. Anything not blocking the first meaningful paint is a secondary concern until the critical path is clean.
- Bytes sent ≠ bytes parsed ≠ bytes executed. Compression hides parse and execute cost. A 50 KB gzipped bundle can still freeze the main thread for 300 ms on a mid-tier phone.
- Re-renders are not free, and they are not the first place to look. Network, parse, and layout usually dominate. Profile before reaching for
memo. - A performance budget is a contract. Without an enforced budget, every regression is "small" and the page gets slower forever.
Core Web Vitals
The three user-centric metrics Google ranks on, plus two supporting metrics. Targets are the "good" thresholds for the 75th percentile of page loads.
| Metric | Measures | Good | Needs improvement | Poor |
|---|---|---|---|---|
| LCP (Largest Contentful Paint) | Time to render the largest visible element | ≤ 2.5 s | ≤ 4.0 s | > 4.0 s |
| INP (Interaction to Next Paint) | Worst interaction latency on the page | ≤ 200 ms | ≤ 500 ms | > 500 ms |
| CLS (Cumulative Layout Shift) | Sum of unexpected layout shift scores | ≤ 0.1 | ≤ 0.25 | > 0.25 |
| FCP (First Contentful Paint) | Time to first text/image paint | ≤ 1.8 s | ≤ 3.0 s | > 3.0 s |
| TTFB (Time to First Byte) | Server response start time | ≤ 0.8 s | ≤ 1.8 s | > 1.8 s |
Capturing the metrics
In production, attribute every metric to the page and interaction that produced it:
import { onLCP, onINP, onCLS, onFCP, onTTFB } from 'web-vitals/attribution';
onLCP(({ name, value, attribution }) => {
send({
metric: name,
value,
element: attribution.element, // CSS selector of the LCP element
url: attribution.url, // image / font URL if applicable
timeToFirstByte: attribution.timeToFirstByte,
resourceLoadDelay: attribution.resourceLoadDelay,
resourceLoadTime: attribution.resourceLoadTime,
elementRenderDelay: attribution.elementRenderDelay,
});
});
Attribution data is the difference between "LCP is 4 s" and "LCP is 4 s because the hero image waited 2.8 s for a render-blocking stylesheet".
LCP — Largest Contentful Paint
LCP fires when the largest above-the-fold element finishes painting. It is almost always one of: a hero image, a poster frame, a block of text, or a video first frame.
Decomposition
LCP breaks into four phases. Optimise the dominant one.
| Phase | What it is | Typical fix |
|---|---|---|
| TTFB | Server response | Edge cache, CDN, faster origin |
| Resource load delay | Time from TTFB until the LCP resource starts loading | Preload, remove render-blocking deps, fetch earlier |
| Resource load time | Bytes over the wire | Smaller image, modern format, correct sizes |
| Element render delay | Time after the resource is loaded until it paints | Unblock the main thread, defer non-critical JS/CSS |
Image LCP
<!-- Above-the-fold hero -->
<img
src="hero-1200.avif"
srcset="hero-600.avif 600w, hero-1200.avif 1200w, hero-2000.avif 2000w"
sizes="(min-width: 1024px) 1200px, 100vw"
width="1200" height="675"
fetchpriority="high"
decoding="async"
alt="...">
fetchpriority="high"on the LCP image only — overusing it cancels the signal.widthandheightare mandatory; missing dimensions cause CLS.- Preload only when the image is discovered late (e.g. set by JS or CSS):
<link rel="preload" as="image" href="hero-1200.avif" imagesrcset="hero-600.avif 600w, hero-1200.avif 1200w" imagesizes="(min-width: 1024px) 1200px, 100vw" fetchpriority="high">
Text LCP
If the LCP element is text, the bottleneck is usually the font:
font-display: swap(paint with fallback, swap when loaded) oroptional(paint with fallback, never swap if slow).- Preload the one critical font subset, woff2 only.
- Self-host. Third-party font CDNs add a DNS + TLS + TCP cost on every cold load.
What blocks LCP
- Render-blocking CSS in
<head>. Inline the critical CSS; defer the rest. - Synchronous
<script>in<head>withoutdeferorasync. - Client-rendered hero (LCP element ships in JS). Server-render the hero markup even in a SPA.
INP — Interaction to Next Paint
INP measures the worst interaction on the page (p98 of click/tap/keypress → next paint). The metric replaced FID because FID only measured the first input.
Decomposition
| Phase | What it is | Typical fix |
|---|---|---|
| Input delay | Time before the handler runs | Cut long tasks already on the main thread |
| Processing time | The handler itself | useTransition, useDeferredValue, web workers, smaller work |
| Presentation delay | Time from handler return to next paint | Avoid layout thrash, batch DOM writes, virtualise lists |
Patterns that wreck INP
- A click handler that triggers a synchronous render of 5 000 list items.
- An
onChangethat filters a large array on every keystroke. - A
useEffectthat runs heavy work after every render. - A third-party tag that registers a long-running
requestIdleCallback.
Yielding to the main thread
Break long tasks. The browser cannot handle input while a task is running.
async function processBatch(items) {
for (const item of items) {
work(item);
if (navigator.scheduling?.isInputPending?.() || shouldYield()) {
await new Promise(r => setTimeout(r)); // yield
}
}
}
function shouldYield() {
return performance.now() - lastYield > 50; // 50 ms task budget
}
Modern alternative: scheduler.yield() where supported, falling back to setTimeout(0).
React-specific INP levers
useTransitionfor state updates that don't need to be synchronous (filter input, tab switch).useDeferredValueto render an expensive list against a stale value while typing.- Move pure transform work out of render — into a memoised selector or a worker.
- Profile with the React DevTools Profiler in Record why each component rendered.
CLS — Cumulative Layout Shift
Any element that moves after its initial paint contributes to CLS. The score is the sum of impact × distance for each unexpected shift.
The fixes are mechanical
- Images, videos, iframes: always set
width+height(or aspect-ratio CSS). - Web fonts: use
size-adjust,ascent-override,descent-override,line-gap-overrideon the fallback@font-faceto match metrics so the swap doesn't reflow. - Ads, embeds, late-arriving content: reserve space with
min-heightoraspect-ratiobefore the content loads. - Banner/cookie injection: render server-side or at the top of
<body>before paint — never insert above existing content after paint. - Skeletons: must match the final layout's dimensions. A skeleton that shifts when content loads is its own CLS source.
CLS only counts unexpected shifts. User-initiated shifts (clicking "show more") within 500 ms are excluded.
JavaScript Bundle
The bundle is the single largest lever on TTI, INP, and main-thread time on cold loads.
Measure first
| Tool | Use for |
|---|---|
source-map-explorer / webpack-bundle-analyzer / rollup-plugin-visualizer | What is in the bundle, by source file |
| Chrome DevTools Coverage panel | What fraction of shipped JS/CSS actually executed on this route |
| Chrome DevTools Performance → Bottom-Up by URL | Which scripts cost main-thread time |
import-cost (editor plugin) | Per-import size at write time |
Coverage of < 50% on a route's bundle means half the shipped JS is dead weight on that route.
Splitting strategy
Ship the minimum to render the current route. Defer the rest.
// Route-level split (the default boundary)
const Dashboard = lazy(() => import('./Dashboard'));
// Component-level split for heavy, conditional UI
const Chart = lazy(() => import('./Chart')); // only loaded when shown
const PdfViewer = lazy(() => import('./PdfViewer'));
// Library-level split for one-off heavy deps
button.onclick = async () => {
const { default: confetti } = await import('canvas-confetti');
confetti();
};
Rules:
- Route boundary is the default split point. Splitting smaller introduces waterfalls unless paired with prefetch.
- Prefetch the next likely route during idle time (
<link rel="prefetch">or framework router hints). - Don't split inside the critical path of the current route. A
lazy()boundary above the LCP element delays LCP.
Tree shaking that actually works
- Side-effect-free packages:
"sideEffects": falseinpackage.json(or list the files that do have side effects). - Named imports only:
import { debounce } from 'lodash-es', neverimport _ from 'lodash'. - ESM source, not CJS. Many CJS packages are unshakeable.
- Production build with minification — tree shaking and dead-code elimination both run there.
Heavy deps with smaller alternatives
| Heavy | Lighter | When to switch |
|---|---|---|
moment | date-fns, dayjs, Intl.DateTimeFormat | Always |
lodash (full) | lodash-es named imports, native methods | Always |
axios | fetch + small wrapper | If you only need JSON + interceptors |
chart.js / recharts | Lightweight SVG, uPlot for time series | Many small charts |
| Full icon packs | Per-icon imports, inline SVG | Always for tree-shakable icon libs |
Don't swap a dependency without measuring before and after.
Performance budget
Set a hard byte budget per route and enforce it in CI:
Initial JS (gzipped): ≤ 170 KB
Initial CSS (gzipped): ≤ 50 KB
LCP image (any format): ≤ 200 KB
Total transfer to LCP: ≤ 500 KB
Tools: bundlesize, size-limit, Lighthouse CI assertions, or framework-native budgets (Next.js experimental.bundlePagesRouterDependencies, Angular budgets).
React Render Performance
Re-renders are rarely the largest cost. Profile first, optimise second.
Profiling
- React DevTools → Profiler → record an interaction.
- Sort by Render duration.
- For each expensive component, open "Why did this render?" — it lists the props/state/hook that changed.
- Only fix the components that appear in the top of the flamegraph and have an explainable change cause.
Re-render causes and fixes
| Cause | Symptom | Fix |
|---|---|---|
| New object/array/function in props every render | Child memo defeated | useMemo / useCallback only if the child is memo()-wrapped and the cost is real |
| Context value changes too often | Every consumer re-renders | Split the context into independent contexts, or memoise the value |
| Parent re-renders cause whole subtree to re-render | Cheap children re-render in a tight loop | Lift state down, or memoise the subtree |
Inline useState initializer is expensive | First render slow | useState(() => expensive()) (lazy initializer) |
| Heavy derivation in render | Render duration high | useMemo, or move to a selector |
memo, useMemo, useCallback are not free. They add comparison and allocation cost. Apply them where a profile shows a real saving, not as a default.
Lists
A list of N items where each row has its own state is one of the highest-leverage perf surfaces.
- Stable
key— never the array index for reorderable lists; use the item's own id. - Virtualise above ~100 visible-or-near-visible rows. Use a virtualisation library (e.g.
@tanstack/react-virtual) in the consuming app — this library ships no virtualiser. content-visibility: autofor long, scrolling, non-virtualised content gives the browser permission to skip layout/paint until in view.- Avoid
useEffectper row when one effect on the list would do.
When to escape React
Some work belongs outside the render tree:
- Animation that runs every frame → CSS,
requestAnimationFrame, or a transform-only animation library. - Heavy parsing/transform → web worker (
Comlinkmakes the ergonomics tolerable). - DOM measurements driving layout →
ResizeObserverinstead of measuring on every render.
Network and Delivery
The waterfall
Open DevTools → Network → reload with cache disabled and "Slow 4G" throttling. Look for:
- A single resource on the critical path that blocks everything after it.
- A chain (script A → script B → fetch C → render) where each step waits for the previous.
- Sequential connections to many origins (each costs DNS + TLS).
Resource hints
| Hint | When |
|---|---|
<link rel="preconnect"> | Origin you will fetch from soon (fonts, API). At most 4 — each costs a connection. |
<link rel="dns-prefetch"> | Cheaper than preconnect; use for origins you might hit. |
<link rel="preload"> | Resource the browser would discover late (font, hero image set by CSS, JSON the SPA fetches). |
<link rel="prefetch"> | Next likely navigation. Low priority, fetched during idle. |
<link rel="modulepreload"> | ES module the current page depends on. |
preload is for this navigation; prefetch is for the next one. Mixing them up either wastes bandwidth or misses the window.
Caching
| Resource | Strategy |
|---|---|
Hashed asset (app.abc123.js) | Cache-Control: public, max-age=31536000, immutable |
| HTML | Cache-Control: no-cache (revalidate every load) or short max-age + stale-while-revalidate |
| API JSON | Per-endpoint. ETag + Cache-Control: private, max-age=N, stale-while-revalidate=M for safe replays |
Service workers add an offline and instant-load layer for repeat visits. Cost: cache invalidation complexity. Add when warranted, not by default.
Third-party scripts
Each one adds parse, execute, and often network time on a domain you don't control.
- Inventory them. Tag manager > 100 KB is a smell, not a feature.
- Defer where possible (
async,defer, or load post-LCP via an event). - Sandbox with Partytown when the script needs
windowbut blocks the main thread. - Replace analytics SDKs with a minimal sendBeacon shim where the SDK is the bottleneck.
Fonts
Fonts are render-blocking by default. Each unoptimised font is +200–500 ms LCP on slow networks.
- Self-host. Avoid the third-party DNS + TLS + TCP penalty.
- woff2 only. Drop woff/ttf/eot fallbacks unless legacy browsers are in scope.
- Subset to the glyphs you actually use (Latin, Latin-Ext) — UnicodeRange separates files per script.
- One weight per family in the critical path. Lazy-load others.
font-display: swapfor body,optionalif you can tolerate the fallback sticking on slow connections.- Match fallback metrics with
size-adjust,ascent-override,descent-overrideto prevent CLS at swap time. - Preload only the one font on the critical text path:
<link rel="preload" as="font" type="font/woff2" href="/fonts/inter-var-latin.woff2" crossorigin>
Images
- Modern format with fallback: AVIF → WebP → JPEG/PNG. Most CDNs (Cloudflare Images, Imgix, Cloudinary, Next/Image, etc.) negotiate this automatically.
- Responsive
srcset+sizes— the browser picks the smallest source that fills the slot. A 2000×2000 image rendered at 200×200 is a 100× waste. - Always set
widthandheight(oraspect-ratio) to reserve space. loading="lazy"for below-the-fold images; never on the LCP image.decoding="async"for non-LCP images.- Strip metadata, quantise, and re-encode. A 5 MB JPEG out of a phone camera is almost always under 200 KB after re-encoding with no visible loss.
CSS
- Inline the critical CSS for the first viewport (≤ 14 KB so it fits in the first TCP slow-start packet).
- Defer the rest with
media="print"swap or arel="preload"+onloadswap. - Avoid
@importin CSS — it serialises requests. - Drop unused rules. Coverage panel shows them; PurgeCSS / Tailwind's JIT remove them at build time.
- Reduce specificity wars; the cascade is fast, your selectors don't need to be.
- Avoid
* { ... }rules with expensive properties (filters, box-shadow).
Measurement Tooling
| Tool | Best for | Caveat |
|---|---|---|
| CrUX / RUM | What real users experience | Aggregated, slow to update |
| Lighthouse (CI or DevTools) | Reproducible lab snapshot, prioritised audits | Single device profile; not field truth |
| WebPageTest | Detailed waterfall, filmstrip, multiple locations | Lab only |
| Chrome DevTools Performance | Frame-level diagnosis of one interaction | Local hardware only |
| Chrome DevTools Coverage | Unused JS/CSS per route | Doesn't catch deferred-but-still-unused |
| React DevTools Profiler | Re-render flamegraph | React-only |
web-vitals library | RUM with attribution | Needs a sink (analytics endpoint) |
| PerformanceObserver | Custom timing in code | Per-metric API surface differs |
Lab vs field
Use field data (CrUX, RUM) to rank what to fix — it reflects the device, network, and user mix you actually have.
Use lab data (Lighthouse, WebPageTest, DevTools) to diagnose one specific page or regression — reproducible, attributable, but unrepresentative.
A site that scores 100 in Lighthouse and has poor CrUX numbers has a measurement problem, not a performance one. Find the device/network combination the field data is reporting on, then reproduce in the lab.
Performance Budget
A budget that isn't enforced is a wish. Wire it into CI.
# size-limit.config.json (example)
[
{ "path": "dist/app-*.js", "limit": "170 KB", "gzip": true },
{ "path": "dist/app-*.css", "limit": "50 KB", "gzip": true },
{ "path": "dist/vendor-*.js", "limit": "120 KB", "gzip": true }
]
# Lighthouse CI assertions (example)
assertions:
categories:performance: ['error', { minScore: 0.9 }]
largest-contentful-paint: ['error', { maxNumericValue: 2500 }]
cumulative-layout-shift: ['error', { maxNumericValue: 0.1 }]
total-blocking-time: ['error', { maxNumericValue: 200 }]
Run the budget on every PR. Fail the build on regression. The first failure will be loud — that's the point.
Audit
Run in order on the site or app in scope. Report findings as Blocker / High / Medium with the rule each violates.
1. Field metrics
- CrUX (or equivalent RUM) is collected and reviewed; the LCP / INP / CLS p75 for the top 5 templates is known.
- A dashboard segments metrics by device class (mobile / desktop) and connection.
2. LCP
- The LCP element is identified for each top template.
- The LCP image (if any) has correct
width,height, modern format, responsivesrcset, andfetchpriority="high"only when justified. - No render-blocking script in
<head>withoutdefer/async/ module. - Critical CSS is inlined or fits in the first response.
3. INP
- No interaction handler runs a synchronous task > 50 ms on a mid-tier device.
- Heavy state updates use
useTransitionoruseDeferredValue(React). - Third-party tags do not register long tasks during interaction windows.
4. CLS
- Every
<img>,<video>,<iframe>haswidth+heightor aspect-ratio. - Fallback font metrics match the web font (
size-adjust,ascent-override, …). - Late-injected banners/ads have reserved space.
5. Bundle
- An initial-JS budget exists, is enforced in CI, and is currently green.
- Bundle analyzer output shows no duplicated large dependencies, no
moment, no fulllodash, no debug-only code in production. - Coverage panel reports ≥ 50 % usage on the critical route's initial JS.
- Route splits exist; component splits don't sit on the LCP critical path.
6. React renders
- No top-of-profiler component re-renders without a real prop/state change.
- Lists > 100 visible/near-visible rows are virtualised or use
content-visibility: auto. memo,useMemo,useCallbackare present only where a profile shows a saving.
7. Network
- Resource hints (
preconnect,preload,prefetch) are present, correct, and not overused. - Caching headers are correct: hashed assets immutable, HTML revalidated, API JSON deliberate.
- Third-party scripts are inventoried with owner, purpose, byte cost, and main-thread cost.
8. Fonts and images
- Fonts are self-hosted, woff2-only, subset, and have
font-displayset. - Images use a modern format, responsive
srcset, lazy-load below the fold, eager-load LCP.
9. Observability
web-vitals(or equivalent) is wired to a sink with attribution.- Long tasks and slow interactions are sampled and queryable.
- A regression in any Core Web Vital triggers an alert.
Spec template
Use in Design mode. Fill every section.
Surface: <route / page / feature>
Primary device: <mobile mid-tier / desktop / both>
Critical user: <what the user is here to do>
Budget:
Initial JS (gzip): ≤ <KB>
Initial CSS (gzip): ≤ <KB>
LCP image: ≤ <KB>
Total to LCP: ≤ <KB>
Targets (p75 field):
LCP: ≤ <ms>
INP: ≤ <ms>
CLS: ≤ <score>
Critical path:
LCP element: <selector / role>
Render strategy: <SSR / SSG / streamed SSR / CSR-with-skeleton>
Above-the-fold JS: <list of bundles>
Above-the-fold CSS: <inline critical / external>
Fonts on path: <list, woff2, subset, preload?>
Loading strategy:
Route splits: <where>
Component splits: <where, with what fallback>
Prefetch on idle: <which next routes>
Resource hints: <preconnect, preload, prefetch list>
Interaction performance:
Heavy interactions: <list>
Yielding / transitions: <which use useTransition / scheduler / worker>
Lists requiring virtual: <where, expected row count>
Measurement:
Field RUM: <library, sink, dashboards>
Lab CI: <Lighthouse CI / WebPageTest, asserted budgets>
Regression gate: <which budgets fail the build>
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |