Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Fundamentals
  1. 1.Introduction to React & Development Environment
  2. 2.JSX, Components & Props
  3. 3.Managing Component State with useState
  4. 4.Event Handling & Conditional Rendering
  5. 5.Rendering Lists & Basic useEffect
  6. 6.Deep Dive into useEffect Hook
  7. 7.useRef and useReducer for Complex State
  8. 8.Optimizing Performance with useMemo & useCallback
  9. 9.Context API & Custom Hooks for Reusability
  10. 10.Client-Side Routing with React Router
  11. 11.Forms, Validation & Data Fetching Patterns
  12. 12.Advanced Performance Optimization & Reconciliation
  13. 13.State Management Libraries (Redux Toolkit & Alternatives)
  14. 14.Testing React Components with Jest & React Testing Library
  15. 15.Advanced React Features & Modern Concepts
React Fundamentals
12

React · Lesson 12 of 15 · 4 min

Advanced Performance Optimization & Reconciliation

This is how you answer "How would you optimize this React app?" with confidence and precision.

How React Decides to Re-render

When state or props change, React doesn't immediately touch the DOM. It first calls your component functions to create a new tree of elements in memory. This is the "render phase."

Then, it compares this new tree to the old one. This comparison, called "reconciliation" or "diffing," follows simple, fast heuristics. Knowing them is key.

  1. Different component types? The old tree is thrown away, and the new one is built from scratch. State is lost. A <div> becoming a <span> causes a full teardown and rebuild of everything inside it.
  2. Same component type? React keeps the underlying DOM node and just updates the attributes that changed (e.g., className, style). It then moves on to diff the children.
  3. Lists of children? This is where the key prop is critical. The key tells React which child is which across renders. Without a stable, unique key, React has to guess.

The trap: Using an array index for a key (items.map((item, index) => <li key={index}>...)). If you prepend an item to the list, every single item gets a new index. React thinks every component needs to be updated with new props, which can destroy performance and lead to subtle bugs with component state. Always use a stable ID from your data.

Find the Bottleneck Before You Fix It

The most common mistake is "premature optimization." Do not start wrapping components in React.memo just because you can. You will add complexity and may even make performance worse.

Your first step is always to profile.

Use the React DevTools Profiler to record interactions in your app. It will generate a flamegraph showing which components rendered and why they took so long. Look for components that re-render frequently even when their visual output doesn't change. These are your targets.

In an interview, your first sentence when asked about optimization should be, "I'd start by using the React DevTools Profiler to identify the actual bottleneck." This immediately signals a professional, data-driven approach, not a guess-and-check one.

Your Core Optimization Toolkit

Once you've identified an unnecessarily re-rendering component, you have three primary tools. They all work by caching (or "memoizing") something, preventing re-computation or re-rendering if the inputs are the same.

React.memo

This is a higher-order component that prevents a component from re-rendering if its props haven't changed. It does a shallow comparison of the props object.

Use it on "pure" components that render the same output for the same props and are rendered often with the same props while their parent re-renders for other reasons.

useCallback

This hook memoizes a function definition. Without it, any function you define inside your component body is recreated on every single render.

If you pass a freshly created function to a React.memo-wrapped child, the memoization is useless. The prop is a new reference every time, so the child re-renders. useCallback gives you a stable function reference across renders, as long as its dependencies don't change.

useMemo

This hook memoizes the result of a function call. Use it for two main reasons:

  1. To avoid re-running an expensive calculation on every render.
  2. To preserve the reference of an object or array that you pass as a prop to a memoized child. Just like with functions, const style = { color: 'blue' } creates a new object reference on every render.

The trade-off: All memoization trades CPU for memory. You are storing the previous result or function. The comparison itself also has a small cost. If the component is simple or its props change on every render anyway, React.memo is just dead weight. Use these tools surgically, not everywhere.

import React, { useState, useCallback } from 'react';

// This component is wrapped in React.memo.
// It will only re-render if its props have shallowly changed.
const ProductCard = React.memo(({ name, onAddToCart }: { name: string; onAddToCart: () => void; }) => {
  console.log(`Rendering ProductCard: ${name}`);
  return (
    <div>
      <h3>{name}</h3>
      <button onClick={onAddToCart}>Add to Cart</button>
    </div>
  );
});

function ProductList() {
  const [filter, setFilter] = useState('');

  // This function is memoized. It will not be recreated when `filter` changes,
  // preventing the "Laptop" ProductCard from re-rendering unnecessarily.
  const handleAddToCart = useCallback(() => {
    console.log('Adding Laptop to cart');
  }, []); // Empty dependency array: created once.

  return (
    <div>
      <input
        type="text"
        placeholder="Filter..."
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
      />
      <ProductCard name="Laptop" onAddToCart={handleAddToCart} />
      <ProductCard name="Mouse" onAddToCart={() => console.log('Adding Mouse')} />
    </div>
  );
}

In this example, typing in the input re-renders ProductList. The "Mouse" ProductCard will re-render every time because it gets a new inline function. The "Laptop" card will not, because handleAddToCart is a stable reference thanks to useCallback.

Optimizing for Scale

For truly large applications, component-level memoization isn't enough. You need to think bigger.

Virtualization (or "Windowing"): If you need to render a list with thousands of items, don't render them all. That would create thousands of DOM nodes and kill browser performance. Instead, render only the handful of items currently visible in the viewport (plus a small buffer). Libraries like react-window handle the complex calculations for you. This is the standard answer for optimizing long lists.

Code-Splitting: Your initial JavaScript bundle doesn't need to include code for every single page and feature of your app. Use React.lazy() and <Suspense> to load components on demand. This is most commonly done at the route level. A smaller initial bundle means a faster time-to-interactive, a critical performance metric.

Try it

Find a component in one of your projects that renders a list. Ensure every item has a stable, unique key (not the index). Now, use the Profiler to see what happens when you add an item to the list. Does the whole list re-render, or just the new item? If the whole list re-renders, apply React.memo to the list item component and see if that fixes it. If not, find the unstable prop (it's probably a callback) and memoize it.

Next: State Management Libraries (Redux Toolkit & Alternatives)

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Forms, Validation & Data Fetching Patterns

Next

State Management Libraries (Redux Toolkit & Alternatives)