mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
755 lines
30 KiB
HTML
755 lines
30 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>frontend-frontend-performance</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/frontend-frontend-performance.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/frontend-frontend-performance">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/frontend-frontend-performance.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>frontend-frontend-performance</h1><p class="lede">Optimizing application performance</p><h1>Frontend Performance</h1>
|
|
<p><strong>Scope</strong>: Bundle optimization, code splitting, image optimization, Core Web Vitals, lazy loading <strong>Lines</strong>: ~310 <strong>Last Updated</strong>: 2025-10-18</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Optimizing application performance</li><li>Reducing bundle size</li><li>Improving Core Web Vitals</li><li>Implementing lazy loading</li><li>Optimizing images and assets</li><li>Diagnosing performance issues</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Core Web Vitals</h3>
|
|
<p><strong>LCP</strong> (Largest Contentful Paint) - Loading performance</p>
|
|
<ul><li>Target: < 2.5 seconds</li><li>Measures: Time to render largest content</li></ul>
|
|
<p><strong>FID</strong> (First Input Delay) - Interactivity</p>
|
|
<ul><li>Target: < 100ms</li><li>Measures: Time from interaction to response</li></ul>
|
|
<p><strong>CLS</strong> (Cumulative Layout Shift) - Visual stability</p>
|
|
<ul><li>Target: < 0.1</li><li>Measures: Unexpected layout shifts</li></ul>
|
|
<p><strong>INP</strong> (Interaction to Next Paint) - Replacing FID</p>
|
|
<ul><li>Target: < 200ms</li><li>Measures: Overall responsiveness</li></ul>
|
|
<hr>
|
|
<h2>Bundle Optimization</h2>
|
|
<h3>Analyze Bundle Size</h3>
|
|
<pre><code class="lang-bash"># Next.js
|
|
npm run build
|
|
# Output shows bundle sizes
|
|
|
|
# Webpack Bundle Analyzer
|
|
npm install --save-dev webpack-bundle-analyzer
|
|
|
|
# Vite
|
|
npm run build
|
|
vite-bundle-visualizer</code></pre>
|
|
<h3>Code Splitting</h3>
|
|
<p><strong>Route-based splitting</strong> (automatic in Next.js):</p>
|
|
<pre><code class="lang-tsx">// app/dashboard/page.tsx
|
|
// Automatically code-split by route
|
|
export default function Dashboard() {
|
|
return <div>Dashboard</div>;
|
|
}</code></pre>
|
|
<p><strong>Component-based splitting</strong>:</p>
|
|
<pre><code class="lang-tsx">import { lazy, Suspense } from 'react';
|
|
|
|
// Lazy load heavy component
|
|
const HeavyChart = lazy(() => import('./components/HeavyChart'));
|
|
|
|
function Dashboard() {
|
|
return (
|
|
<div>
|
|
<Suspense fallback={<div>Loading chart...</div>}>
|
|
<HeavyChart />
|
|
</Suspense>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<p><strong>Dynamic imports</strong>:</p>
|
|
<pre><code class="lang-tsx">// Load library only when needed
|
|
async function handleExport() {
|
|
const { exportToPDF } = await import('./lib/pdf-export');
|
|
exportToPDF(data);
|
|
}</code></pre>
|
|
<h3>Tree Shaking</h3>
|
|
<pre><code class="lang-tsx">// ❌ Bad: Imports entire library
|
|
import _ from 'lodash';
|
|
_.debounce(fn, 300);
|
|
|
|
// ✅ Good: Import only what you need
|
|
import debounce from 'lodash/debounce';
|
|
debounce(fn, 300);
|
|
|
|
// ✅ Better: Use modern alternative
|
|
import { debounce } from 'es-toolkit';</code></pre>
|
|
<h3>Remove Unused Code</h3>
|
|
<pre><code class="lang-tsx">// ❌ Bad: Importing unused code
|
|
import { Button, Card, Table, Modal, Tabs } from 'ui-library';
|
|
// Only using Button
|
|
|
|
// ✅ Good: Only import what's used
|
|
import { Button } from 'ui-library';</code></pre>
|
|
<p><strong>Tools</strong>:</p>
|
|
<ul><li>ESLint <code>no-unused-vars</code></li><li>Webpack <code>sideEffects: false</code> in package.json</li><li>PurgeCSS for unused CSS</li></ul>
|
|
<hr>
|
|
<h2>Image Optimization</h2>
|
|
<h3>Next.js Image Component</h3>
|
|
<pre><code class="lang-tsx">import Image from 'next/image';
|
|
|
|
// ❌ Bad: Regular img tag
|
|
<img src="/photo.jpg" alt="Photo" />
|
|
|
|
// ✅ Good: Next.js Image (automatic optimization)
|
|
<Image
|
|
src="/photo.jpg"
|
|
alt="Photo"
|
|
width={800}
|
|
height={600}
|
|
priority // Load eagerly (above fold)
|
|
/>
|
|
|
|
// Responsive image
|
|
<Image
|
|
src="/photo.jpg"
|
|
alt="Photo"
|
|
fill
|
|
sizes="(max-width: 768px) 100vw, 50vw"
|
|
style={{ objectFit: 'cover' }}
|
|
/></code></pre>
|
|
<p><strong>Benefits</strong>:</p>
|
|
<ul><li>Automatic WebP/AVIF conversion</li><li>Lazy loading by default</li><li>Responsive images</li><li>Blur placeholder</li></ul>
|
|
<h3>Image Formats</h3>
|
|
<pre><code>Format | Use Case | Savings vs PNG
|
|
----------|--------------------|--------------
|
|
WebP | General purpose | 25-35%
|
|
AVIF | Modern browsers | 50%
|
|
PNG | Transparency | Baseline
|
|
JPEG | Photos | Smaller than PNG
|
|
SVG | Icons, logos | Scalable</code></pre>
|
|
<h3>Lazy Loading</h3>
|
|
<pre><code class="lang-tsx">// Images (native)
|
|
<img src="photo.jpg" loading="lazy" alt="Photo" />
|
|
|
|
// Next.js Image (lazy by default)
|
|
<Image src="/photo.jpg" alt="Photo" width={800} height={600} />
|
|
|
|
// Eager loading (above fold)
|
|
<Image src="/hero.jpg" alt="Hero" width={1200} height={600} priority /></code></pre>
|
|
<h3>Image Optimization Tools</h3>
|
|
<pre><code class="lang-bash"># Compress images
|
|
npx @squoosh/cli --webp auto *.jpg
|
|
|
|
# Optimize SVGs
|
|
npx svgo *.svg
|
|
|
|
# Generate responsive images
|
|
npx sharp-cli resize 800 600 --input photo.jpg --output photo-800.jpg</code></pre>
|
|
<hr>
|
|
<h2>JavaScript Optimization</h2>
|
|
<h3>Debouncing and Throttling</h3>
|
|
<pre><code class="lang-tsx">import { debounce } from 'es-toolkit';
|
|
|
|
function SearchInput() {
|
|
const [query, setQuery] = useState('');
|
|
|
|
// Debounce API calls
|
|
const debouncedSearch = useMemo(
|
|
() => debounce((value: string) => {
|
|
fetch(`/api/search?q=${value}`);
|
|
}, 300),
|
|
[]
|
|
);
|
|
|
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const value = e.target.value;
|
|
setQuery(value);
|
|
debouncedSearch(value);
|
|
};
|
|
|
|
return <input value={query} onChange={handleChange} />;
|
|
}</code></pre>
|
|
<pre><code class="lang-tsx">import { throttle } from 'es-toolkit';
|
|
|
|
function ScrollTracker() {
|
|
const handleScroll = useMemo(
|
|
() => throttle(() => {
|
|
console.log('Scroll position:', window.scrollY);
|
|
}, 100),
|
|
[]
|
|
);
|
|
|
|
useEffect(() => {
|
|
window.addEventListener('scroll', handleScroll);
|
|
return () => window.removeEventListener('scroll', handleScroll);
|
|
}, [handleScroll]);
|
|
|
|
return <div>Content</div>;
|
|
}</code></pre>
|
|
<h3>Memoization</h3>
|
|
<pre><code class="lang-tsx">import { memo, useMemo, useCallback } from 'react';
|
|
|
|
// Memoize expensive component
|
|
const ExpensiveList = memo(function ExpensiveList({ items }: { items: Item[] }) {
|
|
return (
|
|
<ul>
|
|
{items.map(item => (
|
|
<li key={item.id}>{item.name}</li>
|
|
))}
|
|
</ul>
|
|
);
|
|
});
|
|
|
|
// Memoize expensive computation
|
|
function ProductList({ products }: { products: Product[] }) {
|
|
const sortedProducts = useMemo(() => {
|
|
return [...products].sort((a, b) => b.price - a.price);
|
|
}, [products]);
|
|
|
|
return <div>{sortedProducts.map(p => <div key={p.id}>{p.name}</div>)}</div>;
|
|
}
|
|
|
|
// Memoize callbacks
|
|
function TodoList({ todos }: { todos: Todo[] }) {
|
|
const [filter, setFilter] = useState('all');
|
|
|
|
const handleToggle = useCallback((id: string) => {
|
|
// Toggle todo logic
|
|
}, []);
|
|
|
|
return (
|
|
<div>
|
|
{todos.map(todo => (
|
|
<TodoItem key={todo.id} todo={todo} onToggle={handleToggle} />
|
|
))}
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<p><strong>When to memoize</strong>:</p>
|
|
<ul><li>Expensive calculations</li><li>Large lists</li><li>Stable callback references for child components</li><li>NOT for cheap operations (overhead > benefit)</li></ul>
|
|
<h3>Virtual Lists</h3>
|
|
<pre><code class="lang-tsx">import { useVirtualizer } from '@tanstack/react-virtual';
|
|
|
|
function VirtualList({ items }: { items: Item[] }) {
|
|
const parentRef = useRef<HTMLDivElement>(null);
|
|
|
|
const virtualizer = useVirtualizer({
|
|
count: items.length,
|
|
getScrollElement: () => parentRef.current,
|
|
estimateSize: () => 50, // Estimated row height
|
|
});
|
|
|
|
return (
|
|
<div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
|
|
<div style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }}>
|
|
{virtualizer.getVirtualItems().map(virtualItem => (
|
|
<div
|
|
key={virtualItem.index}
|
|
style={{
|
|
position: 'absolute',
|
|
top: 0,
|
|
left: 0,
|
|
width: '100%',
|
|
height: `${virtualItem.size}px`,
|
|
transform: `translateY(${virtualItem.start}px)`,
|
|
}}
|
|
>
|
|
{items[virtualItem.index].name}
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<p><strong>Use when</strong>:</p>
|
|
<ul><li>Rendering >100 items</li><li>Items have consistent height</li><li>Scrolling performance is critical</li></ul>
|
|
<hr>
|
|
<h2>CSS Optimization</h2>
|
|
<h3>Critical CSS</h3>
|
|
<pre><code class="lang-tsx">// app/layout.tsx
|
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html>
|
|
<head>
|
|
{/* Inline critical CSS */}
|
|
<style dangerouslySetInnerHTML={{ __html: criticalCSS }} />
|
|
</head>
|
|
<body>{children}</body>
|
|
</html>
|
|
);
|
|
}</code></pre>
|
|
<h3>CSS-in-JS Performance</h3>
|
|
<pre><code class="lang-tsx">// ❌ Bad: Inline styles (no caching, creates new object every render)
|
|
<div style={{ color: 'red', fontSize: 16 }}>Text</div>
|
|
|
|
// ✅ Good: CSS modules or Tailwind (cached, reusable)
|
|
<div className="text-red-500 text-base">Text</div>
|
|
|
|
// ✅ Good: Extract constant styles
|
|
const styles = { color: 'red', fontSize: 16 };
|
|
<div style={styles}>Text</div></code></pre>
|
|
<h3>Remove Unused CSS</h3>
|
|
<pre><code class="lang-tsx">// Tailwind CSS (automatic purging)
|
|
// tailwind.config.js
|
|
module.exports = {
|
|
content: [
|
|
'./app/**/*.{js,ts,jsx,tsx}',
|
|
'./components/**/*.{js,ts,jsx,tsx}',
|
|
],
|
|
// Purges unused classes in production
|
|
};</code></pre>
|
|
<hr>
|
|
<h2>Network Optimization</h2>
|
|
<h3>Prefetching</h3>
|
|
<pre><code class="lang-tsx">import Link from 'next/link';
|
|
|
|
// Next.js prefetches linked pages on hover
|
|
<Link href="/dashboard" prefetch={true}>
|
|
Dashboard
|
|
</Link>
|
|
|
|
// Manual prefetch
|
|
import { useRouter } from 'next/navigation';
|
|
|
|
function NavItem() {
|
|
const router = useRouter();
|
|
|
|
return (
|
|
<button
|
|
onMouseEnter={() => router.prefetch('/dashboard')}
|
|
onClick={() => router.push('/dashboard')}
|
|
>
|
|
Dashboard
|
|
</button>
|
|
);
|
|
}</code></pre>
|
|
<h3>Resource Hints</h3>
|
|
<pre><code class="lang-tsx">// app/layout.tsx
|
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html>
|
|
<head>
|
|
{/* Preconnect to external domains */}
|
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
<link rel="preconnect" href="https://api.example.com" />
|
|
|
|
{/* DNS prefetch */}
|
|
<link rel="dns-prefetch" href="https://cdn.example.com" />
|
|
|
|
{/* Preload critical resources */}
|
|
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />
|
|
</head>
|
|
<body>{children}</body>
|
|
</html>
|
|
);
|
|
}</code></pre>
|
|
<h3>Caching Strategies</h3>
|
|
<pre><code class="lang-tsx">// Next.js fetch with caching
|
|
async function getData() {
|
|
// Static (cached forever)
|
|
const res = await fetch('https://api.example.com/data', {
|
|
cache: 'force-cache'
|
|
});
|
|
|
|
// Dynamic (no cache)
|
|
const res = await fetch('https://api.example.com/data', {
|
|
cache: 'no-store'
|
|
});
|
|
|
|
// Revalidate (time-based)
|
|
const res = await fetch('https://api.example.com/data', {
|
|
next: { revalidate: 60 } // Revalidate every 60 seconds
|
|
});
|
|
|
|
return res.json();
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Rendering Optimization</h2>
|
|
<h3>Server Components (Next.js)</h3>
|
|
<pre><code class="lang-tsx">// ✅ Server Component (default)
|
|
async function PostList() {
|
|
const posts = await getPosts(); // Fetches on server
|
|
|
|
return (
|
|
<div>
|
|
{posts.map(post => (
|
|
<PostCard key={post.id} post={post} />
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ✅ Client Component (when needed)
|
|
'use client';
|
|
|
|
import { useState } from 'react';
|
|
|
|
function InteractiveButton() {
|
|
const [count, setCount] = useState(0);
|
|
return <button onClick={() => setCount(count + 1)}>{count}</button>;
|
|
}</code></pre>
|
|
<p><strong>Server Components benefits</strong>:</p>
|
|
<ul><li>Zero JavaScript sent to client</li><li>Direct database access</li><li>Automatic code splitting</li></ul>
|
|
<h3>Streaming and Suspense</h3>
|
|
<pre><code class="lang-tsx">import { Suspense } from 'react';
|
|
|
|
export default function Page() {
|
|
return (
|
|
<div>
|
|
<h1>Dashboard</h1>
|
|
|
|
{/* Fast component renders immediately */}
|
|
<UserGreeting />
|
|
|
|
{/* Slow component streams in */}
|
|
<Suspense fallback={<Spinner />}>
|
|
<SlowAnalytics />
|
|
</Suspense>
|
|
|
|
<Suspense fallback={<Spinner />}>
|
|
<SlowRecentOrders />
|
|
</Suspense>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Performance Monitoring</h2>
|
|
<h3>Web Vitals Tracking</h3>
|
|
<pre><code class="lang-tsx">// app/components/WebVitals.tsx
|
|
'use client';
|
|
|
|
import { useReportWebVitals } from 'next/web-vitals';
|
|
|
|
export function WebVitals() {
|
|
useReportWebVitals((metric) => {
|
|
console.log(metric);
|
|
|
|
// Send to analytics
|
|
fetch('/api/analytics', {
|
|
method: 'POST',
|
|
body: JSON.stringify(metric),
|
|
});
|
|
});
|
|
|
|
return null;
|
|
}
|
|
|
|
// app/layout.tsx
|
|
import { WebVitals } from './components/WebVitals';
|
|
|
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html>
|
|
<body>
|
|
{children}
|
|
<WebVitals />
|
|
</body>
|
|
</html>
|
|
);
|
|
}</code></pre>
|
|
<h3>Performance Profiling</h3>
|
|
<pre><code class="lang-tsx">// React DevTools Profiler
|
|
import { Profiler } from 'react';
|
|
|
|
function onRenderCallback(
|
|
id: string,
|
|
phase: 'mount' | 'update',
|
|
actualDuration: number,
|
|
baseDuration: number,
|
|
startTime: number,
|
|
commitTime: number
|
|
) {
|
|
console.log({ id, phase, actualDuration });
|
|
}
|
|
|
|
<Profiler id="Dashboard" onRender={onRenderCallback}>
|
|
<Dashboard />
|
|
</Profiler></code></pre>
|
|
<h3>Browser Performance API</h3>
|
|
<pre><code class="lang-tsx">// Measure custom metrics
|
|
performance.mark('data-fetch-start');
|
|
await fetchData();
|
|
performance.mark('data-fetch-end');
|
|
|
|
performance.measure('data-fetch', 'data-fetch-start', 'data-fetch-end');
|
|
|
|
const measure = performance.getEntriesByName('data-fetch')[0];
|
|
console.log('Fetch took:', measure.duration, 'ms');</code></pre>
|
|
<hr>
|
|
<h2>Font Optimization</h2>
|
|
<h3>Next.js Font Optimization</h3>
|
|
<pre><code class="lang-tsx">// app/layout.tsx
|
|
import { Zen, ZenMono } from '@hanzo/font';
|
|
|
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html className={`${Zen.variable} ${ZenMono.variable}`}>
|
|
<body>{children}</body>
|
|
</html>
|
|
);
|
|
}
|
|
|
|
// globals.css
|
|
body {
|
|
font-family: var(--font-zen-sans), ui-sans-serif, system-ui, sans-serif;
|
|
}
|
|
|
|
code {
|
|
font-family: var(--font-zen-mono), ui-monospace, monospace;
|
|
}</code></pre>
|
|
<p><strong>Benefits</strong>:</p>
|
|
<ul><li>Self-hosted fonts (no external request)</li><li>Automatic font subsetting</li><li>Zero layout shift</li></ul>
|
|
<h3>Font Loading Strategies</h3>
|
|
<pre><code class="lang-css">/* font-display: swap - Show fallback, swap when loaded */
|
|
@font-face {
|
|
font-family: 'CustomFont';
|
|
src: url('/fonts/custom.woff2');
|
|
font-display: swap;
|
|
}
|
|
|
|
/* font-display: optional - Use only if cached */
|
|
@font-face {
|
|
font-family: 'OptionalFont';
|
|
src: url('/fonts/optional.woff2');
|
|
font-display: optional;
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Core Web Vitals Targets</h3>
|
|
<pre><code>LCP (Largest Contentful Paint): < 2.5s
|
|
FID (First Input Delay): < 100ms
|
|
CLS (Cumulative Layout Shift): < 0.1
|
|
INP (Interaction to Next Paint): < 200ms</code></pre>
|
|
<h3>Optimization Checklist</h3>
|
|
<pre><code>[ ] Code splitting (route-based, component-based)
|
|
[ ] Image optimization (Next.js Image, WebP/AVIF)
|
|
[ ] Lazy loading (images, components)
|
|
[ ] Bundle size < 200KB (initial load)
|
|
[ ] Memoization (React.memo, useMemo, useCallback)
|
|
[ ] Virtual lists (for >100 items)
|
|
[ ] Remove unused code (tree shaking)
|
|
[ ] Prefetch linked pages
|
|
[ ] Resource hints (preconnect, dns-prefetch)
|
|
[ ] Font optimization (self-hosted, subsetting)
|
|
[ ] Critical CSS inlined
|
|
[ ] Streaming and Suspense
|
|
[ ] Server Components (where possible)</code></pre>
|
|
<h3>Performance Tools</h3>
|
|
<pre><code>Chrome DevTools Lighthouse
|
|
WebPageTest
|
|
PageSpeed Insights
|
|
Next.js Bundle Analyzer
|
|
React DevTools Profiler
|
|
Web Vitals Chrome Extension</code></pre>
|
|
<hr>
|
|
<h2>Common Anti-Patterns</h2>
|
|
<p>❌ <strong>Large bundle sizes</strong>: Split code, remove unused dependencies ✅ Analyze and optimize bundle</p>
|
|
<p>❌ <strong>Unoptimized images</strong>: Use Next.js Image component ✅ Automatic optimization</p>
|
|
<p>❌ <strong>Blocking scripts</strong>: Use async/defer or move to end of body ✅ Non-blocking script loading</p>
|
|
<p>❌ <strong>No lazy loading</strong>: Load everything upfront ✅ Lazy load non-critical content</p>
|
|
<p>❌ <strong>Premature optimization</strong>: Optimize without measuring ✅ Profile first, then optimize</p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>react-component-patterns.md</code> - Memoization, code splitting</li><li><code>nextjs-app-router.md</code> - Server Components, streaming</li><li><code>react-data-fetching.md</code> - Caching, prefetching</li><li><code>web-accessibility.md</code> - Performance affects accessibility</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-18 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/frontend-frontend-performance.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |