Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

Optimizing Calculations with useMemo

React applications frequently perform calculations while rendering. For example, a student management application may filter thousands of student records, sort course information, calculate fee totals, or process other large collections of data.

When a component renders again because its state changes, these calculations normally execute again. If the calculation is expensive and its inputs have not changed, repeating the same work may waste processing time.

React provides the useMemo Hook to cache the result of a calculation between renders. When the dependencies remain unchanged, React can reuse the previous result instead of executing the calculation again.

Learning Objectives: After completing this lesson, you will understand the purpose of useMemo, its syntax, dependency arrays, expensive calculations, student filtering, product sorting, the difference between useMemo and React.memo, and common memoization mistakes.

1. What Is useMemo?

useMemo is a React Hook that lets you cache the result of a calculation between renders. React calls the calculation function when necessary and can reuse the previously calculated value when its dependencies have not changed.

Suppose an institute maintains 5,000 student records. A user types a search term to find a student. Filtering the records may require processing many entries. If another unrelated state value changes, repeating the same filtering operation may be unnecessary.

With useMemo, the filtered list can be reused while the search term and student data remain unchanged.

Component Renders
↓
Check Dependencies
↓
Dependencies Unchanged?
↓
Reuse Cached Result

If a dependency changes, React recalculates the value.

Important: useMemo is a performance optimization, not a replacement for state. Your application must still produce the correct result if React recalculates the value.

2. Syntax of useMemo

To use useMemo, import it from React and provide a calculation function followed by a dependency array.

Basic Syntax
import { useMemo } from "react";

const result = useMemo(() => {
    return performCalculation();
}, [dependency1, dependency2]);

The syntax contains three important parts:

  • Calculation function: Performs the calculation and returns the value to be cached.
  • Dependency array: Contains the reactive values used by the calculation.
  • Returned result: The calculated value that the component uses to display its UI.

Understanding the Dependency Array

Syntax Behavior
useMemo(() => calculate(), [value]) The calculation can be reused while value remains unchanged.
useMemo(() => calculate(), []) No reactive dependencies are listed. The cached result can be reused across ordinary re-renders.
useMemo(() => calculate()) Without a dependency array, the calculation runs on every render.
Always include every reactive value used by the calculation in the dependency array. Missing dependencies can cause the component to reuse a result based on outdated values.

3. Example Without useMemo

First, consider a component that calculates the total of five numbers. The component also contains a counter. Whenever the counter changes, React renders the component again, and the total calculation runs again.

In this example, the numbers array is declared outside the component. This keeps the input data stable so that we can compare the normal calculation with the memoized calculation fairly.

CalculationExample.jsx — Without useMemo
import { useState } from "react";

const numbers = [10, 20, 30, 40, 50];

function calculateTotal(numbers) {
    console.log("Calculating total...");

    return numbers.reduce((total, number) => {
        return total + number;
    }, 0);
}

function CalculationExample() {
    const [count, setCount] = useState(0);

    const total = calculateTotal(numbers);

    return (
        <div>
            <h2>Total: {total}</h2>
            <h3>Counter: {count}</h3>

            <button onClick={() => setCount(c => c + 1)}>
                Increase Counter
            </button>
        </div>
    );
}

export default CalculationExample;

Expected Output

Total: 150

Counter: 0

Button: Increase Counter

When the user clicks Increase Counter, the counter updates and the message "Calculating total..." appears again because the calculation runs during the next render.

Step-by-Step Explanation

  1. React renders the CalculationExample component.
  2. calculateTotal adds 10, 20, 30, 40, and 50.
  3. The calculation returns 150.
  4. The user clicks Increase Counter.
  5. setCount updates the counter and causes another render.
  6. calculateTotal executes again, although the numbers have not changed.
The calculation in this example is small and inexpensive. It demonstrates the concept clearly; memoization is most useful when repeated calculations have a meaningful performance cost.

4. Example With useMemo

Now we will optimize the previous example using useMemo. Because the numbers array is a module-level constant, it does not change between renders. Therefore, an empty dependency array is appropriate for this particular calculation.

CalculationExample.jsx — With useMemo
import { useMemo, useState } from "react";

const numbers = [10, 20, 30, 40, 50];

function calculateTotal(numbers) {
    console.log("Calculating total...");

    return numbers.reduce((total, number) => {
        return total + number;
    }, 0);
}

function CalculationExample() {
    const [count, setCount] = useState(0);

    const total = useMemo(() => {
        return calculateTotal(numbers);
    }, []);

    return (
        <div>
            <h2>Total: {total}</h2>
            <h3>Counter: {count}</h3>

            <button onClick={() => setCount(c => c + 1)}>
                Increase Counter
            </button>
        </div>
    );
}

export default CalculationExample;

Expected Behavior

Initial display: Total: 150, Counter: 0.

After one click: Total: 150, Counter: 1.

After two clicks: Total: 150, Counter: 2.

The counter changes normally, but React can reuse the cached total instead of recalculating it on every counter update.

What Changed?

  • The calculateTotal function is called inside useMemo.
  • The dependency array is empty because the numbers array is constant.
  • The calculation result is stored as the memoized value.
  • Counter updates do not change the calculation dependencies.
React Strict Mode may call the calculation more than once during development checks. Do not rely on a calculation running exactly once. The calculation should be pure and safe to repeat.

5. Practical Example: Filtering Students

A student management system may contain many student records. Users need to search for a particular student by name. We can use useMemo to cache the filtered list while the search term remains unchanged.

StudentSearch.jsx
import { useMemo, useState } from "react";

const students = [
    "Samadhan",
    "Samiksha",
    "Aarav",
    "Priya",
    "Rahul",
    "Sneha"
];

function StudentSearch() {
    const [search, setSearch] = useState("");
    const [count, setCount] = useState(0);

    const filteredStudents = useMemo(() => {
        console.log("Filtering students...");

        return students.filter(student =>
            student.toLowerCase().includes(
                search.toLowerCase()
            )
        );
    }, [search]);

    return (
        <div>
            <h2>CIIT Training Institute

            <ul>
                {filteredStudents.map(student => (
                    <li key={student}>{student}</li>
                ))}
            </ul>
        </div>
    );
}

export default StudentSearch;

How Does This Example Work?

  1. The students array contains six student names.
  2. The search state stores the text entered by the user.
  3. useMemo filters the student list using the current search value.
  4. When the search value changes, the calculation runs again.
  5. When only the counter changes, the search dependency remains unchanged.
  6. React can reuse the previously filtered list during the counter update.

Expected Output

Initially: All six students are displayed.

When the user searches for "Sam":

  • Samadhan
  • Samiksha

Clicking the counter does not require the student filtering calculation to run again. Changing the search text recalculates the filtered result.

6. Practical Example: Sorting Products

Consider an application displaying products with their prices. Users can sort the products from lowest to highest price or from highest to lowest price. The sorting calculation needs to run when the sort order changes, but not necessarily when an unrelated counter changes.

ProductList.jsx
import { useMemo, useState } from "react";

const products = [
    { id: 1, name: "Keyboard", price: 1200 },
    { id: 2, name: "Mouse", price: 500 },
    { id: 3, name: "Monitor", price: 8500 },
    { id: 4, name: "Headphones", price: 1800 }
];

function ProductList() {
    const [ascending, setAscending] = useState(true);
    const [count, setCount] = useState(0);

    const sortedProducts = useMemo(() => {
        return [...products].sort((a, b) => {
            return ascending
                ? a.price - b.price
                : b.price - a.price;
        });
    }, [ascending]);

    return (
        <div>
            <h2>Product List</h2>

            <button onClick={() => setAscending(value => !value)}>
                Toggle Sort Order
            </button>

            <button onClick={() => setCount(c => c + 1)}>
                Counter: {count}
            </button>

            <ul>
                {sortedProducts.map(product => (
                    <li key={product.id}>
                        {product.name} - ₹{product.price}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default ProductList;

Expected Output: Ascending Price

  1. Mouse — ₹500
  2. Keyboard — ₹1200
  3. Headphones — ₹1800
  4. Monitor — ₹8500

Understanding the Dependencies

The sortedProducts calculation depends on ascending. When the user clicks Toggle Sort Order, ascending changes and React recalculates the sorted list. When only the counter changes, ascending remains the same and React can reuse the cached result.

The example uses [...products] before sorting. This creates a copy of the array so that sort does not mutate the original module-level products array.

7. Understanding Dependencies Correctly

The dependency array tells React which reactive values are used by the calculation. If any dependency changes, React recalculates the result. Dependencies are compared using Object.is.

CalculationWithDependencies.jsx
import { useMemo, useState } from "react";

function PriceCalculator() {
    const [price, setPrice] = useState(100);
    const [quantity, setQuantity] = useState(2);

    const total = useMemo(() => {
        console.log("Calculating total...");

        return price * quantity;
    }, [price, quantity]);

    return (
        <div>
            <h2>Price: ₹{price}</h2>
            <h2>Quantity: {quantity}</h2>
            <h2>Total: ₹{total}</h2>

            <button onClick={() => setPrice(p => p + 10)}>
                Increase Price
            </button>

            <button onClick={() => setQuantity(q => q + 1)}>
                Increase Quantity
            </button>
        </div>
    );
}

export default PriceCalculator;

Expected Output

Initial values: Price ₹100, Quantity 2, Total ₹200.

After Increase Price: Price ₹110, Quantity 2, Total ₹220.

After Increase Quantity: Price ₹110, Quantity 3, Total ₹330.

Both price and quantity are included in the dependency array because the calculation uses both values. If either changes, React recalculates the total so that the displayed result remains correct.

8. useMemo vs useState

Although both Hooks are used inside function components, they have different purposes. useState stores information that changes over time, while useMemo caches the result of a calculation based on existing values.

Feature useState useMemo
Main purpose Store component state. Cache a calculation result.
Typical values Counter, search text, selected tab. Filtered list, sorted list, calculated total.
Update behavior Calling the state setter requests an update. React recalculates when dependencies change.
Role in correctness Stores application state. Should remain safe to recalculate.

9. useMemo vs React.memo

These two APIs are related to memoization, but they optimize different things. React.memo can skip rendering a component when its props are unchanged, whereas useMemo caches the result of a calculation.

React.memo useMemo
Memoizes a component. Memoizes a calculation result.
Can skip a child render when its props are unchanged. Can reuse a value when its dependencies are unchanged.
Useful for suitable child components. Useful for expensive calculations and derived values.
memo(Component) useMemo(() => calculate(), [dependency])

10. Common Mistakes with useMemo

Mistake 1: Using useMemo for Every Calculation

Small calculations may be faster to run directly. Memoization adds complexity, so use it when there is a meaningful performance reason.

Mistake 2: Missing Dependencies

If the calculation uses a changing state or prop that is missing from the dependency array, the cached result can become outdated.

Mistake 3: Unstable Dependencies

Creating a new object or array inside the component and using it as a dependency can cause the calculation to run again on every render because its reference changes.

Mistake 4: Mutating Existing Data

A useMemo calculation should be pure. Avoid changing external variables or mutating existing arrays and objects while rendering. Create a copy when an operation such as sorting would otherwise modify the original array.

Mistake 5: Treating the Cache as Permanent Storage

useMemo is a performance optimization, not a replacement for state, refs, or persistent storage. React may recalculate the value when needed.

11. Best Practices

  • Use useMemo when a calculation is expensive enough to matter.
  • Include all reactive dependencies used by the calculation.
  • Keep calculations pure and avoid mutating existing data.
  • Use React Developer Tools Profiler to identify actual bottlenecks.
  • Measure performance before and after applying an optimization.
  • Keep the code simple when memoization provides no meaningful benefit.

12. Practice Tasks

Task 1: Calculate a Total

Create a component that calculates the total of an array of numbers. Add an unrelated counter and compare how often the calculation runs before and after using useMemo.

Task 2: Search Students

Create a list of ten students and use useMemo to filter them by name. Verify that the filtered result changes when the search text changes.

Task 3: Sort Products

Create a product list with names and prices. Use useMemo to sort the products in ascending and descending order.

Task 4: Multiple Dependencies

Create a calculation that depends on two state values. Include both dependencies in useMemo and observe what happens when each value changes.

Task 5: Compare the Hooks

Explain the difference between useMemo, useState, and React.memo. Write one practical example for each.

Summary

The useMemo Hook caches the result of a calculation between renders while its dependencies remain unchanged. It is useful for expensive operations such as filtering student lists, sorting products, and calculating totals. Correct dependency arrays ensure that calculations update when relevant inputs change, while pure calculations keep rendering predictable. Unlike useState, useMemo does not store application state, and unlike React.memo, it memoizes a value rather than a component. At CIIT Training Institute, students should practise these examples and measure performance before deciding whether memoization provides a real benefit.