StackPractices
intermediate By Mathias Paulenko

Complete Guide to React Performance Optimization

Optimize React apps for speed. Covers memoization, virtualization, code splitting, bundle analysis, React Profiler, concurrent features, and Core Web Vitals.

Introduction

React ships fast. The reconciler is good, the scheduler is good, and for most apps the framework does its job without anyone thinking about it. The performance problems show up later — after the app has grown, after someone wraps every list in context, after the bundle quietly doubles because a charting library ended up on the home page.

This guide is for that moment: Lighthouse scores sliding, a 60fps animation turning into a slideshow on a mid-range phone, a table with 5,000 rows that takes seconds to scroll. The through-line is simple — profile first, memoize later. React’s defaults are already sensible, and most “optimizations” people reach for (wrapping everything in useMemo, memoizing every component) cost more than they save. What follows walks through how to measure where the time actually goes, then covers the techniques that matter once you know: memoization, virtualization, code splitting, bundle analysis, state management, and the concurrent features built for exactly this kind of problem.

When to Use This Guide

This guide is aimed at intermediate React developers working on an app that already exists and already feels slow — or whose metrics are trending the wrong way. If you can read a component tree and you’ve got a production build to measure, everything here applies. You don’t need to be a performance specialist; you do need a profiler and an honest baseline.

Skip it, or at least skim it, in a few cases. If your app is small, renders fast, and scores green on Core Web Vitals, nothing here will make it meaningfully faster — premature optimization is real work that produces no user-visible gain. If the slowness lives on the server (slow API responses, database queries, cold starts), React is the wrong layer; fix the backend first and come back if the client is still the bottleneck. And if you’re still learning React fundamentals, get comfortable with rendering and state before adding memoization on top — optimizing a mental model you don’t have yet just makes the confusion more expensive.

Measurement First: How to Find the Real Bottleneck

Before touching a single useMemo, find out where the time goes. Guessing is the most common way teams burn weeks on React performance work — they memoize the component that looked suspicious and discover the real cost was a 4MB bundle or a context provider three levels up.

The workflow I use has four steps, and every technique later in this guide assumes you can do them.

1. Establish a baseline. Record current numbers before changing anything: Lighthouse or PageSpeed Insights for Core Web Vitals, bundle size from your build output, and — for perceived performance — a quick Profiler recording of the interaction that feels slow. Without a baseline you can’t prove a fix worked, and you’ll end up arguing about improvements nobody can measure.

2. Profile the render. In development, open React DevTools and use the Profiler tab. It shows a flamegraph of which components rendered, how long each took, and why — props changed, state changed, context changed, or the parent re-rendered. The React Profiler API does the same thing programmatically when you need it in code or tests, and its docs explain the “why did this render” badges in detail. If you need measurements in code rather than the DevTools UI, the Profiler component wraps any subtree and reports render timing through a callback:

import { Profiler } from "react";

function onRenderCallback(id, phase, actualDuration, baseDuration, startTime, commitTime) {
  console.log(`${id} ${phase} took ${actualDuration}ms`);
}

function App() {
  return (
    <Profiler id="App" onRender={onRenderCallback}>
      <ExpensiveComponent />
    </Profiler>
  );
}

Dev builds run far slower than production, so treat these numbers as relative, not absolute — and remember the Profiler only works in development builds.

3. Profile the browser. Chrome DevTools’ Performance tab records everything React can’t see: script evaluation, layout, paint, long tasks. A lot of “React is slow” reports turn out to be layout thrashing or a heavy dependency, and the Performance tab is where you tell the difference.

4. Measure in production. Dev tools lie a little — development builds behave differently and run much slower. Ship timing data with the web-vitals library or your RUM provider to see LCP, INP, and CLS as real users experience them. Field data is what Google ranks on and what users actually feel; lab data is what you debug with.

Only after you can name the bottleneck — “this list re-renders 5,000 rows on every keystroke” rather than “the app feels slow” — does it make sense to pick a technique. The rest of this guide is organized roughly by where in that pipeline the cost usually hides.

How Re-renders Propagate

Understanding re-renders is the prerequisite for every memoization decision that follows. A component re-renders whenever three things can happen:

  • State change — the component holding the state re-renders, and by default its entire subtree re-renders with it.
  • Parent re-render — when a parent re-renders, React re-renders every child unless something stops it: React.memo, an identical-element bailout, or the child simply not being re-invoked.
  • Context change — every component consuming a context re-renders when that context’s value reference changes, regardless of which field inside it changed.
flowchart diagram: State or props change

That third bullet explains a huge share of React performance bugs in real apps. Context value is compared by reference (Object.is), so value={{ user, theme }} builds a new object every render and notifies every consumer — including consumers that only read theme and never touch user. Splitting contexts and memoizing values (covered under State Management) is often the highest-impact fix available, because one misplaced provider can re-render half the tree on every keystroke.

Memoization

Memoization tells React “this output hasn’t changed, don’t redo the work.” React gives you three tools for it, and they solve different problems — mixing them up is the most common mistake in this whole guide.

React.memo

memo wraps a component and skips re-rendering it when its props are shallowly equal to the previous render. It only helps when the parent re-renders but the child’s inputs didn’t change — which is exactly the situation useCallback and stable references exist to create.

import { memo } from "react";

const ExpensiveCard = memo(function ExpensiveCard({ title, description }) {
  return (
    <div className="card">
      <h3>{title}</h3>
      <p>{description}</p>
    </div>
  );
});

// Custom comparison for cases where shallow equality is too strict
const MemoizedCard = memo(Card, (prevProps, nextProps) => {
  return prevProps.title === nextProps.title && prevProps.description === nextProps.description;
});

The React docs on memo are worth reading before you reach for a custom comparison — a wrong comparator is a subtle bug factory, and shallow equality is right for almost everything.

useMemo

useMemo caches the result of a computation between renders. The rule of thumb: memoize when the computation is expensive and its inputs change less often than the component renders. Filtering or sorting a few hundred items on every keystroke qualifies; concatenating two strings doesn’t.

import { useMemo } from "react";

function ProductList({ products, filter }) {
  const filtered = useMemo(() => {
    return products.filter((p) => p.category === filter);
  }, [products, filter]);

  return (
    <ul>
      {filtered.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}

One caveat worth internalizing: useMemo is a performance hint, not a semantic guarantee. React may discard the cache in some cases — offscreen rendering, future memory pressure — so don’t store values whose correctness depends on the memo surviving. If the app breaks when React throws the cache away, it was never a memo; it was state.

useCallback

useCallback does for functions what useMemo does for values: it returns the same function reference across renders. Its only real use is stabilizing a function passed as a prop to a memoized child — otherwise the child sees a “new” prop every render and memo can’t help.

import { memo, useCallback, useState } from "react";

const MemoizedButton = memo(function MemoizedButton({ onClick, count }) {
  return <button onClick={onClick}>Count: {count}</button>;
});

function Parent() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");

  // Stable reference: MemoizedButton won't re-render on text changes
  const handleClick = useCallback(() => {
    setCount((c) => c + 1);
  }, []);

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <MemoizedButton onClick={handleClick} count={count} />
    </div>
  );
}

The trap here is doing it everywhere. useCallback on a handler passed to a plain <button> buys nothing — the DOM element re-renders anyway. The payoff only exists at the boundary where a memoized component would otherwise be defeated by a fresh function prop, so reach for it there and nowhere else.

When NOT to memoize

This deserves its own paragraph because over-memoization is the failure mode I see most often. Every memo, useMemo, and useCallback adds comparison work on every render; if the thing it protects is cheap, you’ve added cost to save nothing. Skip memoization when:

  • The component is small — a few DOM nodes, no heavy computation. Re-rendering it is quicker than comparing props.
  • Props are primitives that rarely change — React’s default behavior is already fine.
  • The component re-renders anyway because its own state or context changed — memo can’t stop that.
  • The computation inside useMemo is trivial — a + b memoized is slower than just computing it.
  • You’re doing it “just in case.” Profile first; add memo where the flamegraph shows cost.

A useful heuristic: memoize at the edges — expensive leaves, large lists, components sitting under frequently-changing parents. Don’t memoize the trunk.

React Compiler and Automatic Memoization

React 19 ships with the React Compiler, enabled through a Babel plugin (babel-plugin-react-compiler) and increasingly on by default in supporting frameworks. It automatically memoizes components, hook values, and callback props at build time — basically applying the memo/useMemo/useCallback decisions above without you writing them. For teams on React 19+, this changes the calculus: hand-written memoization stops being the first tool and becomes the fallback for cases the compiler can’t prove safe.

What the compiler handles well: components whose props are provably stable, expensive derivations inside components, and callback props passed down the tree. What it doesn’t do: fix architectural problems. A context provider that rebuilds a huge object every render still re-renders every consumer. A 5,000-row list still renders 5,000 rows until you virtualize it. A 4MB bundle is still 4MB. The compiler makes renders cheaper — it doesn’t change what renders.

If you’re on React 19 or evaluating it, the companion guides cover the rest of the release: React 19 features for use(), Actions, and the new hooks, and React Server Components for the rendering model that sidesteps client re-renders entirely.

To verify the compiler is actually helping, run the React DevTools Profiler on the same interaction before and after enabling it, and look at which components bail out. If a component you expected to be memoized isn’t, the compiler likely couldn’t prove its inputs stable — which usually means an inline object or function being created upstream. Manual useMemo still earns its place there, as a targeted fix rather than a blanket policy.

Virtualization (Large Lists)

Rendering 1,000 DOM rows works. Rendering 10,000 doesn’t — layout, style recalc, and memory all scale with node count, and scroll performance collapses long before React itself becomes the bottleneck. Virtualization renders only the visible slice plus a small overscan buffer, positioned absolutely inside a tall spacer element.

Three options cover most cases, and they trade simplicity against flexibility:

ApproachBest forTrade-offs
react-windowFixed-height lists, simplest APIOnly fixed sizes; slower release cadence lately
@tanstack/react-virtualVariable heights, grids, tables, custom scroll containersMore setup; you own more of the positioning math
CSS content-visibility: autoLong documents and pages, minimal JSSlightly less control over measurement; verify browser support

For a fixed-height list where rows are uniform, react-window is still the fastest path to working code — the Virtualize Long Lists with react-window recipe walks through it end to end:

import { FixedSizeList } from "react-window";

function Row({ index, style, data }) {
  return (
    <div style={style}>
      {data[index].name} — {data[index].email}
    </div>
  );
}

function UserList({ users }) {
  return (
    <FixedSizeList
      height={600}
      itemCount={users.length}
      itemSize={50}
      width="100%"
      itemData={users}
    >
      {Row}
    </FixedSizeList>
  );
}

itemData matters more than it looks: passing users through it keeps row props stable across scrolls, so memo-ized rows don’t re-render on every scroll tick. When rows vary in height (chat messages, cards, wrapped table text), reach for @tanstack/react-virtual instead:

import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";

function VariableHeightList({ items }) {
  const parentRef = useRef(null);

  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 80,
    overscan: 5,
  });

  return (
    <div ref={parentRef} style={{ height: 600, 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%",
              transform: `translateY(${virtualItem.start}px)`,
            }}
          >
            {items[virtualItem.index].content}
          </div>
        ))}
      </div>
    </div>
  );
}

The estimateSize doesn’t need to be exact — the virtualizer measures real elements and corrects itself as you scroll — but a closer estimate means less scroll jitter. overscan renders a few extra items above and below the viewport so fast scrolling doesn’t flash empty space; 5–10 is typical.

Before reaching for a library, check whether you need virtualization at all. A long but static list does fine server-rendered with content-visibility: auto and zero JavaScript. And if users need to find arbitrary rows quickly, pagination or search-as-you-type may beat virtualization — virtualized lists are awkward with browser find (Ctrl+F) and need careful ARIA semantics for screen readers, which the libraries mostly handle but you should verify.

Code Splitting

Code splitting is the technique with the best effort-to-impact ratio for most React apps. Instead of one bundle, you split code into chunks loaded on demand — typically per route, per heavy feature, or per rarely-used component.

import { lazy, Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";

const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
const Product = lazy(() => import("./pages/Product"));

function PageLoader() {
  return <div>Loading page...</div>;
}

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<PageLoader />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/product/:id" element={<Product />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}
flowchart diagram: User navigates to route

Two rules matter more than the syntax. First, lazy() must be called at module level — the React docs are explicit that calling it during render creates a new component type each time, which remounts the subtree and can refetch the chunk. Second, every lazy component needs a Suspense boundary above it; without one React throws.

Route-level splitting gives you the biggest wins because most users only visit a few routes. The SPA Code Splitting and Lazy Loading recipe covers the Vite and Rollup side of emitting clean chunks with the right cache headers.

For conditional features — an admin panel, a settings modal, a chart only some users open — split the chunk but keep lazy at module scope:

import { lazy, Suspense } from "react";

// Module scope: created once, not per render
const AdminPanel = lazy(() => import("./AdminPanel"));

function App({ showAdmin }) {
  return (
    <div>
      <Header />
      {showAdmin && (
        <Suspense fallback={<Loader />}>
          <AdminPanel />
        </Suspense>
      )}
    </div>
  );
}

The conditional render pattern matters: mounting <Suspense> only when needed means the fallback doesn’t flash for users who never see the feature, and the chunk is fetched on first open rather than on page load. If you find yourself wanting to call lazy() inside useMemo or useEffect, stop — that’s the anti-pattern this replaces.

Bundle Analysis

Code splitting only helps if you know what’s actually in the bundle. The tooling is mature and cheap: for Vite projects, rollup-plugin-visualizer emits an interactive treemap of every chunk after vite build; for webpack, webpack-bundle-analyzer does the same against dist/stats.json. The bundle size optimization guide goes deep on budgets, dependency auditing, and compression — the short version here is: build with stats, find the largest offenders, and check whether they’re being imported eagerly somewhere they shouldn’t be.

# Vite: the visualizer plugin writes dist/stats.html after build
npm install --save-dev rollup-plugin-visualizer
// vite.config.js
import { visualizer } from "rollup-plugin-visualizer";

export default {
  plugins: [
    visualizer({
      open: true,
      filename: "dist/stats.html",
      gzipSize: true,
    }),
  ],
};

The gzipSize toggle matters — it shows the size users actually download after compression. A 2MB bundle that gzips to 600KB is a different problem than one that gzips to 1.8MB.

Image Optimization

Images are usually the largest bytes on a page and the most common cause of poor LCP. The React-specific part is small but worth getting right: reserve space with explicit dimensions to prevent CLS, lazy-load below-the-fold images, and decode asynchronously so image work doesn’t block the main thread.

import { useState } from "react";

function OptimizedImage({ src, alt, width, height }) {
  const [loaded, setLoaded] = useState(false);

  return (
    <div style={{ width, height, background: "#f0f0f0" }}>
      <img
        src={src}
        alt={alt}
        width={width}
        height={height}
        loading="lazy"
        decoding="async"
        onLoad={() => setLoaded(true)}
        style={{ opacity: loaded ? 1 : 0, transition: "opacity 0.3s" }}
      />
    </div>
  );
}

A few notes on what this does and doesn’t cover. loading="lazy" defers off-screen images until they’re near the viewport — don’t put it on your LCP image (usually the hero), or you’ll delay the metric you’re trying to improve; use fetchpriority="high" there instead. The fixed-dimension wrapper prevents layout shift while the image loads. For anything beyond this — modern formats like AVIF and WebP, responsive srcset, CDN resizing — the answer is usually your image pipeline or a framework’s built-in component (next/image and friends), not hand-rolled React.

State Management Optimization

Global state is where React apps go to accumulate re-renders. Every state library solves the subscription problem differently, and the difference matters more than which library you picked.

Selector optimization (Zustand)

Zustand’s model is simple: components subscribe to slices of state and only re-render when their slice changes. The mistake is subscribing to the whole store — useStore() with no selector re-renders on any state change, which is context behavior with extra steps.

import { create } from "zustand";

const useStore = create((set) => ({
  user: null,
  posts: [],
  setPosts: (posts) => set({ posts }),
}));

// BAD — re-renders on any state change
function PostList() {
  const store = useStore();
  return <div>{store.posts.map((p) => <p key={p.id}>{p.title}</p>)}</div>;
}

// GOOD — only re-renders when posts change
function PostList() {
  const posts = useStore((s) => s.posts);
  return <div>{posts.map((p) => <p key={p.id}>{p.title}</p>)}</div>;
}

When a component needs several fields, select them together with shallow from zustand/shallow so the comparison is by value rather than reference — otherwise you trade one problem for another. The same principle applies to Redux (useSelector with shallowEqual or reselect) and to Jotai or TanStack Query selectors: subscribe narrow, and derive in the component or a memoized selector.

Context splitting

React Context is fine for genuinely global, rarely-changing values — theme, locale, auth session. It becomes a performance problem when frequently-changing state goes into it: every consumer re-renders on every change, and there’s no built-in way to select a slice. The fix is splitting by concern and memoizing the values:

import { createContext, useContext, useMemo, useState } from "react";

// BAD — all consumers re-render when either value changes
const AppContext = createContext();

function BadProvider({ children }) {
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState("light");
  return (
    <AppContext.Provider value={{ user, theme, setUser, setTheme }}>
      {children}
    </AppContext.Provider>
  );
}

// GOOD — split contexts, memoize each value
const UserContext = createContext();
const ThemeContext = createContext();

function AppProvider({ children }) {
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState("light");

  // Without useMemo these objects are rebuilt every render and every
  // consumer re-renders even when its own slice didn't change
  const userValue = useMemo(() => ({ user, setUser }), [user]);
  const themeValue = useMemo(() => ({ theme, setTheme }), [theme]);

  return (
    <UserContext.Provider value={userValue}>
      <ThemeContext.Provider value={themeValue}>
        {children}
      </ThemeContext.Provider>
    </UserContext.Provider>
  );
}

function useUser() {
  const ctx = useContext(UserContext);
  if (!ctx) throw new Error("useUser must be used within AppProvider");
  return ctx;
}

Even done correctly, context has a ceiling: it broadcasts to all consumers. If a slice of state updates on every keystroke and has dozens of consumers across the tree, a store with selectors will outperform context every time. Context is for “everyone needs this sometimes”; stores are for “many components need different slices often.”

Data Fetching with use() and Suspense

React 19’s use() hook reads a promise or context during render and suspends until it resolves — which means data fetching can live in the component tree instead of being orchestrated through useEffect + useState triples. Combined with Suspense boundaries, you get loading states for free and the ability to stream UI as data arrives.

import { Suspense, use } from "react";

// Cache the promise per id so re-renders don't refetch
const userCache = new Map();

function getUser(id) {
  if (!userCache.has(id)) {
    userCache.set(id, fetch(`/api/users/${id}`).then((res) => {
      if (!res.ok) throw new Error("Failed to load user");
      return res.json();
    }));
  }
  return userCache.get(id);
}

function UserProfile({ userId }) {
  const user = use(getUser(userId));
  return <div>{user.name}</div>;
}

function App() {
  return (
    <Suspense fallback={<div>Loading user...</div>}>
      <UserProfile userId="42" />
    </Suspense>
  );
}

The caching matters more than it looks: use() reads whatever you pass it, and if you call fetch inline on each render you’ll fire a request per render. Frameworks like Next.js handle this with request deduplication and cache layers; if you’re hand-rolling, the Map above is the minimum viable version. The React use reference covers the promise-identity rules in detail.

This isn’t a replacement for a data library in every app — TanStack Query still wins on caching, retries, and invalidation — but for simple reads where you mainly want Suspense-driven loading states, use() removes a surprising amount of boilerplate and the “set loading, set data, set error” state machine that causes most fetch bugs.

Concurrent Features (React 18+)

React 18 introduced concurrent rendering, and two hooks expose it directly: useTransition for updates you want to mark as non-urgent, and useDeferredValue for values that should lag behind the input that produced them. Both solve the same user-facing problem — the UI stays responsive while expensive work renders in the background.

useTransition is the explicit version: wrap the expensive state update in startTransition, and React keeps the input responsive while the transition renders at lower priority.

import { useTransition, useState } from "react";

function SearchResults({ allItems }) {
  const [isPending, startTransition] = useTransition();
  const [query, setQuery] = useState("");
  const [filtered, setFiltered] = useState(allItems);

  function handleChange(e) {
    // Urgent: the input itself updates immediately
    setQuery(e.target.value);
    // Non-urgent: the expensive filter can wait
    startTransition(() => {
      const results = allItems.filter((item) =>
        item.name.toLowerCase().includes(e.target.value.toLowerCase())
      );
      setFiltered(results);
    });
  }

  return (
    <div>
      <input value={query} onChange={handleChange} />
      {isPending && <span>Filtering...</span>}
      <ul>
        {filtered.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

useDeferredValue is the declarative version: pass it a value that changes often — usually derived from input — and it returns a version that “lags,” rendering first with the stale value and then re-rendering with the fresh one when React has spare time. It’s ideal when the expensive computation sits downstream of a value whose update timing you don’t control, like a search query prop drilling into a heavy list component.

import { useDeferredValue, useMemo } from "react";

function SearchResults({ query, items }) {
  const deferredQuery = useDeferredValue(query);

  const filtered = useMemo(() => {
    return items.filter((item) =>
      item.name.toLowerCase().includes(deferredQuery.toLowerCase())
    );
  }, [items, deferredQuery]);

  return (
    <ul>
      {filtered.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

The React docs cover both hooks and when to pick which — useTransition when you own the state update, useDeferredValue when the value arrives as a prop.

The honest caveat: these features help when the bottleneck is render priority, not render cost. If a component takes 500ms to render, deferring it keeps the UI responsive but doesn’t make it faster — virtualization or algorithmic fixes are still needed. Profile first; reach for transitions when the flamegraph shows expensive renders triggered by urgent updates.

Core Web Vitals

The three metrics Google uses to measure real-user experience — LCP for loading, INP for interactivity, CLS for visual stability — are covered in depth in the web performance recipe, which includes web-vitals library setup and field-data collection. The React-specific takeaway is short: most CWV failures in React apps trace back to one of three things — a heavy eager bundle delaying LCP, long tasks from unoptimized renders hurting INP, or missing image dimensions and font loading causing CLS. The techniques in this guide map onto those three buckets.

# Quick lab check during development
npx lighthouse https://localhost:3000 --view --preset=desktop

Treat Lighthouse as a smoke test, not the finish line — lab scores on your machine say little about the 75th-percentile field data Google actually ranks. The web.dev vitals reference has the current thresholds and the field-data methodology.

Best Practices

  • Profile before optimizing — find the actual bottleneck before reaching for a technique
  • Memoize only expensive operations — over-memoization adds overhead that exceeds the savings
  • Virtualize lists over ~100–200 items — DOM node count is usually the first wall you hit
  • Split routes and heavy features — users only pay for the code they actually run
  • Use loading="lazy" below the fold, fetchpriority="high" on the LCP image
  • Set image dimensions — prevent layout shift before the image arrives
  • Split context by concern and memoize values — or use a selector-based store for hot state
  • Subscribe narrow in state management — selectors, not whole-store subscriptions
  • Mark non-urgent updates with useTransition — keep inputs responsive during expensive renders
  • Measure field data in production — lab scores and real-user scores diverge more than you’d think

Common Mistakes

  • Memoizing everything — comparison overhead exceeds render savings on cheap components
  • Not using stable keys in lists — index keys cause bugs on reorder and quietly defeat memoization
  • Inline object or array props — a fresh reference every render silently breaks React.memo and context values
  • Calling lazy() inside render or useMemo — creates a new component type per render and remounts the subtree
  • Rendering thousands of DOM nodes — no virtualization, no mercy from the browser
  • Subscribing to whole stores or fat contexts — every unrelated state change re-renders the component
  • Storing derived state in useState — recompute with useMemo or derive during render instead
  • Confusing useMemo/useCallback with semantic guarantees — React can discard memoized values
  • Optimizing without a baseline — you can’t prove an improvement you never measured
  • Treating Lighthouse scores as the goal — they’re a diagnostic, not a KPI

See Also

Frequently Asked Questions

When should I use React.memo vs useMemo vs useCallback?

React.memo wraps a component so it skips re-rendering when its props are unchanged. useMemo caches a computed value inside a component, and useCallback caches a function reference for the same reason — usually to keep a prop stable for a memoized child. None of them make code faster by default; they only pay off when profiling shows a real render cost.

How do I measure React performance?

Start in development with the React DevTools Profiler to see which components render and why, then confirm in the browser with Chrome DevTools' Performance tab for layout and scripting costs. For production truth, ship the web-vitals library or your RUM tool and watch LCP, INP, and CLS as real users experience them — that's the data Google ranks on.

Is memoization still needed with the React Compiler?

Less often, but not never. The compiler auto-memoizes what it can prove safe, which covers most routine cases — but it can't fix bad architecture: giant contexts, values it can't verify, expensive renders that still happen. Keep manual memoization as a targeted tool for the cases the profiler flags, not a default habit.

Can code splitting hurt performance?

It can, if overdone. Each split chunk is a network request, so splitting a component needed on first paint adds latency instead of removing it. Split at natural boundaries — routes, features users may never open — and keep the initial chunk lean. A waterfall of tiny chunks is worse than one slightly larger bundle.

Should I use Server Components instead of client-side optimization?

For apps on a supporting framework like Next.js, Server Components reduce the JavaScript shipped and re-rendered on the client, which sidesteps many of these problems at the source. They don't replace measurement or virtualization — a huge server-rendered list still needs pagination or virtualization — but they often make memoization less necessary. See the React Server Components guide for the full picture.