react-performance
React performance optimization techniques and best practices. Covers memoization, virtualization, code splitting, profiling, React DevTools, bundle optimization, and avoiding common performance pitfalls. USE WHEN: user mentions "React performance", "slow React app", "memoization", "virtualization", "code splitting", "lazy loading", "bundle size", asks about "optimizing React", "React DevTools Profiler", "preventing re-renders" DO NOT USE FOR: React 19 Compiler - use `react-19` skill instead, basic React concepts - use `react` skill instead, testing performance - use `react-testing` skill instead
What this skill does
# React Performance
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `react` topic: `performance` for comprehensive documentation on React performance optimization and profiling techniques.
> **Full Reference**: See [advanced.md](advanced.md) for Profiling with React DevTools, Bundle Optimization, Image Optimization, and Web Workers.
## Memoization
### React.memo
Prevents re-renders when props haven't changed:
```tsx
// Only re-renders when props change (shallow comparison)
const ExpensiveComponent = memo(function ExpensiveComponent({
data,
onItemClick,
}: Props) {
return (
<ul>
{data.map(item => (
<li key={item.id} onClick={() => onItemClick(item.id)}>
{item.name}
</li>
))}
</ul>
);
});
// With custom comparison
const OptimizedComponent = memo(
function OptimizedComponent({ user }: Props) {
return <div>{user.name}</div>;
},
(prevProps, nextProps) => prevProps.user.id === nextProps.user.id
);
```
### When to Use memo
```tsx
// ✅ Good: Expensive component with stable parent
const ExpensiveList = memo(function ExpensiveList({ items }: { items: Item[] }) {
return items.map(item => <ExpensiveItem key={item.id} item={item} />);
});
// ❌ Bad: Simple component, memo overhead not worth it
const SimpleText = memo(function SimpleText({ text }: { text: string }) {
return <span>{text}</span>;
});
// ❌ Bad: Props always change anyway
function Parent() {
// New object on every render - memo is useless!
return <MemoizedChild data={{ value: 1 }} />;
}
```
### useMemo
Memoize expensive calculations:
```tsx
function ProductList({ products, filter }: Props) {
const filteredProducts = useMemo(() => {
return products
.filter(p => p.category === filter.category)
.filter(p => p.price >= filter.minPrice && p.price <= filter.maxPrice)
.sort((a, b) => a.name.localeCompare(b.name));
}, [products, filter.category, filter.minPrice, filter.maxPrice]);
return (
<ul>
{filteredProducts.map(p => <ProductCard key={p.id} product={p} />)}
</ul>
);
}
// ❌ Don't overuse - simple operations don't need memoization
const total = useMemo(() => a + b, [a, b]); // Overkill!
```
### useCallback
Memoize functions to prevent child re-renders:
```tsx
function Parent() {
const [count, setCount] = useState(0);
// ✅ Stable reference for child components
const handleClick = useCallback((id: string) => {
console.log('Clicked:', id);
}, []);
// ✅ Dependencies that change function behavior
const handleSubmit = useCallback((data: FormData) => {
submitWithCount(data, count);
}, [count]);
return (
<>
<ChildComponent onClick={handleClick} />
<Form onSubmit={handleSubmit} />
</>
);
}
```
---
## Virtualization
Render only visible items for large lists:
```tsx
import { FixedSizeList } from 'react-window';
function VirtualList({ items }: { items: Item[] }) {
const Row = ({ index, style }: { index: number; style: CSSProperties }) => (
<div style={style} className="list-item">
{items[index].name}
</div>
);
return (
<FixedSizeList
height={400}
width="100%"
itemCount={items.length}
itemSize={50}
>
{Row}
</FixedSizeList>
);
}
```
### With TanStack Virtual
```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,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: 400, overflow: 'auto' }}>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map((virtualItem) => (
<div
key={virtualItem.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: virtualItem.size,
transform: `translateY(${virtualItem.start}px)`,
}}
>
{items[virtualItem.index].name}
</div>
))}
</div>
</div>
);
}
```
---
## Code Splitting
### Route-based Splitting
```tsx
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<PageLoader />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
```
### Component-based Splitting
```tsx
const HeavyChart = lazy(() => import('./HeavyChart'));
function Dashboard() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>Show Chart</button>
{showChart && (
<Suspense fallback={<ChartSkeleton />}>
<HeavyChart data={data} />
</Suspense>
)}
</div>
);
}
```
### Preloading
```tsx
const Dashboard = lazy(() => import('./Dashboard'));
const preloadDashboard = () => import('./Dashboard');
function NavLink() {
return (
<Link
to="/dashboard"
onMouseEnter={preloadDashboard}
onFocus={preloadDashboard}
>
Dashboard
</Link>
);
}
```
---
## Avoiding Unnecessary Re-renders
### Stable References
```tsx
// ❌ Bad: New object on every render
function Parent() {
return <Child style={{ color: 'red' }} />;
}
// ✅ Good: Stable reference
const style = { color: 'red' };
function Parent() {
return <Child style={style} />;
}
// ✅ Good: useMemo for dynamic values
function Parent({ color }) {
const style = useMemo(() => ({ color }), [color]);
return <Child style={style} />;
}
```
### Component Composition
```tsx
// ❌ Bad: Entire component re-renders on count change
function App() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>{count}</button>
<ExpensiveComponent /> {/* Re-renders on every count change! */}
</div>
);
}
// ✅ Good: Move state down
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
function App() {
return (
<div>
<Counter />
<ExpensiveComponent /> {/* Doesn't re-render! */}
</div>
);
}
// ✅ Good: Pass children as props
function Counter({ children }) {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>{count}</button>
{children} {/* Doesn't re-render! */}
</div>
);
}
```
---
## State Management Optimization
### Batching Updates
```tsx
// React 18+ automatically batches these
function handleClick() {
setCount(c => c + 1);
setFlag(f => !f);
setText('updated');
// Only ONE re-render!
}
```
### Derived State
```tsx
// ❌ Bad: Synchronized state
function Form() {
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]); // Extra re-render!
}
// ✅ Good: Calculate during render
function Form() {
const [items, setItems] = useState([]);
const total = items.reduce((sum, item) => sum + item.price, 0);
}
// ✅ Good: useMemo for expensive calculations
function Form() {
const [items, setItems] = useState([]);
const total = useMemo(
() => items.reduce((sum, item) => sum + item.price, 0),
[items]
);
}
```
---
## Common Pitfalls
| Issue | Cause | Solution |
|-------|-------|----------|
| Slow initial render | Large bundle | Code sRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.