๐Performance Optimization
This is the largest topic and the one interviewers dig into most. The structure: diagnose first, then apply targeted fixes, then verify. Never optimize blind.
10.1The golden rule: measure before optimizing
// React Profiler API โ find slow renders at runtime
import { Profiler } from 'react';
const onRender = (id, phase, actualDuration) => {
if (actualDuration > 16) { // slower than one 60fps frame (16.67ms)
console.warn(`[PERF] ${id} (${phase}) took ${actualDuration.toFixed(2)}ms`);
}
};
<Profiler id="Dashboard" onRender={onRender}>
<Dashboard />
</Profiler>
Tools: React DevTools Profiler (which components re-render and why), Lighthouse (load performance), webpack-bundle-analyzer (what's in your bundle), Chrome Performance tab (long tasks, layout thrash).
Common bottlenecks, most to least frequent:
- Unnecessary re-renders (state management / missing memoization)
- Heavy computations on each render (sorting/filtering large lists inline)
- Large bundle size (missing code splitting)
- Network waterfalls / missing caching
- Third-party scripts (analytics, chat widgets, ads)
10.2Memoization โ the three tools
// React.memo โ skip re-render if props are shallow-equal to last render
const TicketRow = React.memo(function TicketRow({ ticket, onSelect }) {
return <div onClick={() => onSelect(ticket.id)}>{ticket.title}</div>;
});
// useMemo โ cache an expensive computed VALUE between renders
const sortedTickets = useMemo(
() => [...tickets].sort((a, b) => b.createdAt - a.createdAt),
[tickets] // recompute only when tickets changes
);
// useCallback โ cache a FUNCTION reference between renders
const handleSelect = useCallback((id) => setSelectedId(id), []);
The critical interaction: React.memo does a shallow prop comparison. If you pass an inline function (onClick={() => ...}) or inline object/array (style={{...}}) to a memoized child, you create a new reference every render, which defeats the memo โ the child re-renders anyway. useCallback/useMemo on those props is what makes React.memo actually work.
When NOT to memoize: memoization has a cost (comparison + memory). Don't wrap tiny/cheap components or sprinkle useCallback everywhere preemptively. Add it where the profiler shows a real re-render problem. Premature memoization is noise that hurts readability.
Forward-looking note: the React Compiler (formerly "React Forget"), which reached broad availability around 2024โ2025, auto-memoizes at build time โ potentially making most manual
useMemo/useCallback/React.memounnecessary. It's worth knowing it exists and mentioning in interviews; but understand the manual tools regardless, because you'll work in codebases without it for years and interviewers still ask.
10.3Code Splitting & Lazy Loading
Without splitting, users download your entire app to view one page. Split so each user downloads only what they need.
Route-based (80% of the impact):
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./pages/Dashboard'));
<Suspense fallback={<PageSkeleton />}>
<Dashboard />
</Suspense>
Component-based (heavy, below-the-fold, or conditional components):
const Charts = lazy(() => import('./Charts'));
// Only load when the user actually opens the charts tab
{showCharts && <Suspense fallback={<Spinner />}><Charts /></Suspense>}
Named-export interop (lazy expects a default export):
const DataGrid = lazy(() =>
import('./DataGrid').then((m) => ({ default: m.DataGrid }))
);
True viewport lazy-loading with Intersection Observer โ load only as the element approaches the screen:
function useOnScreen(rootMargin = '50px') {
const ref = useRef(null);
const [visible, setVisible] = useState(false);
useEffect(() => {
const obs = new IntersectionObserver(
([entry]) => { if (entry.isIntersecting) { setVisible(true); obs.disconnect(); } },
{ rootMargin }
);
if (ref.current) obs.observe(ref.current);
return () => obs.disconnect();
}, [rootMargin]);
return [ref, visible];
}
Vendor/library splitting (put heavy libs โ charts, editors, maps โ in their own chunks so they're cached separately and don't bloat the main bundle):
// webpack splitChunks cacheGroups
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
charts: { test: /[\\/]node_modules[\\/](recharts|chart\.js)[\\/]/, name: 'charts', priority: 20 },
react: { test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/, name: 'react', priority: 15 },
vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: 10 },
},
},
}
Prefetch on intent โ download the next chunk before the user clicks, so navigation feels instant:
<Link to="/analytics" onMouseEnter={() => import('./pages/Analytics')}>
Analytics
</Link>
Common mistakes: lazy-loading components too small to be worth a separate network request (<~30โ50KB); creating separate chunks for many tiny modules (each is an HTTP request โ HTTP/2 mitigates but doesn't eliminate the overhead). Split by route and by genuinely heavy features.
10.4Keeping the UI responsive during heavy updates (React 18 concurrency)
// useDeferredValue โ let the input stay snappy while an expensive list lags behind
function Search({ items }) {
const [term, setTerm] = useState('');
const deferredTerm = useDeferredValue(term); // updates at low priority
const filtered = useMemo(
() => items.filter((i) => i.title.includes(deferredTerm)),
[items, deferredTerm]
);
return (
<>
<input value={term} onChange={(e) => setTerm(e.target.value)} />
{deferredTerm !== term && <Spinner />}
<List items={filtered} />
</>
);
}
// useTransition โ mark state updates as non-urgent so React can interrupt them
function Tabs() {
const [isPending, startTransition] = useTransition();
const [tab, setTab] = useState('home');
const select = (next) => startTransition(() => setTab(next)); // won't block clicks/typing
return <>{isPending && <Spinner />}{/* render tab */}</>;
}
The difference: useDeferredValue defers a value; useTransition defers a state update and gives you an isPending flag. Both rely on Fiber's interruptible rendering.
10.5Virtual scrolling (windowing) for large lists
Rendering 10,000 rows = 10,000 DOM nodes = slow everything. Render only what's visible (~20โ50 rows) plus a small overscan buffer.
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
function BigList({ items, onSelect }) {
return (
<AutoSizer>
{({ height, width }) => (
<FixedSizeList height={height} width={width}
itemCount={items.length} itemSize={80} overscanCount={5}
itemData={{ items, onSelect }}>
{Row}
</FixedSizeList>
)}
</AutoSizer>
);
}
const Row = React.memo(({ index, style, data }) => (
<div style={style} onClick={() => data.onSelect(data.items[index])}>
{data.items[index].title}
</div>
));
Libraries: react-window (lightweight, fixed/variable size), react-virtualized (heavier, more features), @tanstack/react-virtual (modern, headless). Impact: ~10,000 nodes โ ~30 nodes; render time drops from seconds to tens of milliseconds.
10.6Large datasets (10,000+ items) โ the full playbook
Normalize the data. Store entities in a flat map keyed by id, plus index lists โ so updating one item doesn't touch the whole tree:
// Instead of a nested array you re-map on every change:
{
entities: { users: { 'u1': {...}, 'u2': {...} } }, // O(1) lookup & update
indices: { usersByOrg: { 'org1': ['u1', 'u2'] } }, // relationships as id lists
result: ['u1', 'u2', 'u3'] // ordering
}
// Update one user = replace one entry in entities.users, not re-derive everything.
Paginate rather than loading everything. Fetch 50 per page; prefetch adjacent pages. Prefer cursor-based pagination over offset for large tables โ offset gets slow deep into the dataset because the DB still scans skipped rows:
// cursor-based: pass the last id, DB seeks directly
GET /api/users?cursor=<lastId>&limit=50
Pagination vs infinite scroll: pagination = bounded memory, predictable UX, easy to jump around, preserves position on back-navigation. Infinite scroll = better for feeds/discovery but grows memory unbounded and loses scroll position. For 10k+ operational data, pagination usually wins.
Combine with virtual scrolling for the current page if pages are large.
10.7Frequent state updates (real-time / websockets)
The problem: 1,000 socket messages/second โ 1,000 re-renders/second if handled naively.
Batch in memory, flush on an interval:
function useBatchedUpdates(onFlush, { maxBatch = 50, delay = 100 } = {}) {
const batch = useRef([]);
const timer = useRef(null);
return useCallback((update) => {
batch.current.push(update);
if (batch.current.length >= maxBatch) {
onFlush(batch.current); batch.current = [];
} else if (!timer.current) {
timer.current = setTimeout(() => {
onFlush(batch.current); batch.current = []; timer.current = null;
}, delay);
}
}, [onFlush, maxBatch, delay]);
}
// Now the store updates ~10x/sec instead of 1000x/sec.
Also: debounce/throttle rapid inputs; coalesce multiple updates to the same entity into one; use useTransition so update work can't block user input; normalize so each update is a single-key change.
React 18 automatic batching: multiple
setStatecalls in the same event handler and in promises/timeouts/native handlers are now batched into one render automatically (this was event-handlers-only pre-18). You get some batching for free โ but high-frequency external sources (sockets) still need explicit batching as above.
10.8Lighthouse & Core Web Vitals โ with an important correction
Lighthouse scores load performance via Core Web Vitals. Correction to what I said earlier in our chat: I referenced FID (First Input Delay) as a Core Web Vital. As of March 2024, FID was officially replaced by INP (Interaction to Next Paint) as a Core Web Vital. Use INP now โ this matters, because an interviewer up to date on web performance will notice.
The current Core Web Vitals:
- LCP (Largest Contentful Paint) โ loading. Target < 2.5s. Largest visible element paint time. Fix via: optimize hero image, reduce server response (TTFB), remove render-blocking CSS/JS, preload the LCP resource.
- INP (Interaction to Next Paint) โ responsiveness. Target < 200ms. Measures the latency of all interactions across the page's life (not just the first). Fix via: break up long JS tasks, reduce main-thread work, avoid heavy synchronous handlers, use
useTransition/useDeferredValue, yield to the browser. - CLS (Cumulative Layout Shift) โ visual stability. Target < 0.1. Fix via: set explicit width/height (or
aspect-ratio) on images/embeds/ads, reserve space for dynamic content, avoid inserting content above existing content, usetransformfor animations instead of properties that trigger layout.
Other Lighthouse levers: ship less JS (code splitting, tree shaking), compress/serve modern image formats (WebP/AVIF), lazy-load off-screen images (loading="lazy"), use a CDN, cache aggressively, defer non-critical third-party scripts, preconnect to critical origins.
10.9Request optimization
Deduplicate identical in-flight requests (5 components ask for the same user โ 1 fetch):
const inflight = new Map();
function dedupedFetch(url) {
if (inflight.has(url)) return inflight.get(url);
const p = fetch(url).then(r => r.json()).finally(() => inflight.delete(url));
inflight.set(url, p);
return p;
}
Batch many small requests into one round trip (queue for ~50ms, send as a single /batch call). Cache at multiple layers (browser HTTP cache, react-query/SWR in-memory, server Redis). Prefetch likely-next data. Partial responses โ let the client request only needed fields (?fields=id,title,status) to shrink payloads.
Use a data-fetching library (@tanstack/react-query or SWR) rather than hand-rolling. They give you caching, deduplication, background revalidation (stale-while-revalidate), retries, pagination helpers, and optimistic updates out of the box:
useQuery({
queryKey: ['users', page],
queryFn: () => fetch(`/api/users?page=${page}`).then(r => r.json()),
staleTime: 5 * 60 * 1000,
onSuccess: () => queryClient.prefetchQuery(['users', page + 1], /* ... */),
});
10.10Optimizing under a tight deadline (a framework)
The insight: you don't need perfect performance to ship โ you need good-enough performance + monitoring + a plan.
- Phase 1 (โ1 hr): diagnose. Bundle analyzer + Lighthouse + Profiler. Find the actual bottleneck. Don't guess.
- Phase 2 (1โ2 days): high-impact/low-effort wins. Memoize the top few heavy components; route-based code splitting;
useCallbackon callbacks passed to memoized children;useDeferredValuefor search/filter; virtual scroll for big lists. This is typically ~30โ40% improvement. - Phase 3 (before launch): monitoring. Web Vitals reporting + error boundaries. Ship knowing what to fix next.
- Phase 4 (post-launch): the rest. Bundle trimming, image lazy-loading, deeper caching, DB query work โ driven by real user data.
Impact/effort matrix: do High-impact/Low-effort first (memoization, code splitting). Do High/Medium if time (virtual scroll, bundle trimming). Defer Low-impact/High-effort (SSR migration, advanced caching) to post-launch. Communicate the roadmap to stakeholders so "ship now, optimize with data" is an agreed plan, not a surprise.
๐ง Quiz: Performance Optimization
4 questions1What is the golden rule of performance optimization?
2For rendering a list of 10,000+ rows efficiently, the key technique is:
3Which React 18 hook keeps the UI responsive by marking a state update as non-urgent?
4A common reason 'React.memo isn't working' is: