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
08

React · Lesson 8 of 15 · 3 min

Optimizing Performance with useMemo & useCallback

This is how you explain when, and more importantly when not, to use memoization in React.

After this, you will know exactly why these hooks exist and be able to articulate the specific trade-offs. The goal isn't just to prevent re-renders; it's to do so where it actually matters, without making the code worse.

The Problem: Referential Equality

React re-renders a component when its props or state change. For primitive values like strings or numbers, this is simple: 5 is always 5. For objects, arrays, and functions, JavaScript has a different rule: two objects are only equal if they are the exact same object in memory.

This means a new object or function created during a render is never === to the one from the previous render, even if they are structurally identical.

// Every time the parent component renders...
const user = { name: 'Alex' }; // ...a new object is created.
const handleClick = () => console.log('click'); // ...a new function is created.

If you pass user or handleClick as a prop to a child component wrapped in React.memo, the memoization is useless. React.memo does a shallow comparison of props, sees a "new" object or function, and re-renders the child every single time.

This is the primary problem useMemo and useCallback solve. They give you the same object or function reference across renders, as long as their dependencies haven't changed.

Memoizing Values with useMemo

useMemo caches the result of a function call. React will only re-run the function if something in the dependency array has changed.

The syntax is useMemo(() => computeValue(a, b), [a, b]).

You use it for two main reasons:

  1. Preserving referential equality. This is the most common use case. You wrap an object or array creation in useMemo so you can pass a stable reference to a memoized child component.
  2. Skipping an expensive calculation. This is rare. A calculation is only "expensive" if it noticeably blocks the main thread (think >5-10ms). Filtering a few hundred items is not expensive. Complex data aggregation on a huge dataset might be.

In an interview, emphasize the first point. It shows you understand how React rendering actually works. The "expensive calculation" reason is valid but often overused by junior developers. Acknowledging its rarity shows seniority.

Memoizing Functions with useCallback

useCallback caches the function definition itself. It's syntactic sugar for useMemo.

These two are equivalent:

const memoizedFn = useCallback(() => { doSomething(a, b) }, [a, b]);

const memoizedFn = useMemo(() => () => { doSomething(a, b) }, [a, b]);

Use useCallback because it's cleaner. Its main purpose is to pass a stable function reference to a memoized child component or as a dependency to another hook like useEffect.

The trap: The dependency array is critical. If you omit a dependency your function needs (like a piece of state), it will create a stale closure. The function will forever reference the value of that state from the initial render, leading to subtle and frustrating bugs. If you're unsure, the eslint-plugin-react-hooks package is essential for catching these mistakes automatically.

A Realistic Example: The Memoized List

This example shows how useMemo and useCallback work together with React.memo to prevent wasted renders in a list. Typing in the "Add Task" input re-renders TaskListManager, but it does not re-render the individual TaskItem components.

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

interface Task {
  id: number;
  text: string;
  completed: boolean;
}

// The child component is memoized. It will only re-render if its props change.
const TaskItem = memo(({ task, onToggle }: { task: Task; onToggle: (id: number) => void; }) => {
  console.log(`Rendering TaskItem: ${task.text}`);
  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={task.completed}
          onChange={() => onToggle(task.id)}
        />
        {task.text}
      </label>
    </div>
  );
});

function TaskListManager() {
  const [tasks, setTasks] = useState<Task[]>([
    { id: 1, text: 'Learn React', completed: true },
    { id: 2, text: 'Memoize components', completed: false },
  ]);
  const [newTodoText, setNewTodoText] = useState('');

  // This function is passed to each TaskItem. Without useCallback, a new
  // instance would be created on every render of TaskListManager, causing
  // every TaskItem to re-render, even when just typing in the input.
  const handleToggle = useCallback((id: number) => {
    setTasks(currentTasks =>
      currentTasks.map(task =>
        task.id === id ? { ...task, completed: !task.completed } : task
      )
    );
  }, []); // Empty deps: this function's logic never needs to change.

  return (
    <div>
      <input
        type="text"
        value={newTodoText}
        onChange={(e) => setNewTodoText(e.target.value)}
        placeholder="Unrelated input"
      />
      {tasks.map(task => (
        <TaskItem
          key={task.id}
          task={task}
          onToggle={handleToggle} // Passing the stable, memoized function
        />
      ))}
    </div>
  );
}

The Decision Flow

Memoization is not free. It adds complexity and uses memory. Don't apply it blindly. Use this mental model to decide if you need it.

Try it

Refactor a component that renders a list of items where each item has a delete button. Wrap the list item component in React.memo and use useCallback for the delete handler passed from the parent. Add a separate counter state in the parent and verify that clicking the counter does not cause the list items to re-render.

Next: We'll cover how to share state without prop drilling using the Context API & Custom Hooks for Reusability.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

useRef and useReducer for Complex State

Next

Context API & Custom Hooks for Reusability