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

useMemo Hook

Learn how to use the useMemo Hook to cache calculated values between renders and avoid unnecessary recalculation when the relevant dependencies have not changed.

1. What Is the useMemo Hook?

The useMemo Hook is a built-in React Hook that caches the result of a calculation between renders. React recalculates the value when one of its dependencies changes.

It can be useful when a component performs an expensive calculation and the inputs to that calculation often remain unchanged between renders.

Remember: useMemo is a performance optimization. Your component should still produce the correct result without relying on the cached value for correctness.

2. Syntax of useMemo

The basic syntax is:

const cachedValue = useMemo(() => {
    return calculateValue();
}, [dependencies]);
  • Calculation function: Returns the value that React should cache.
  • Dependencies: Values used by the calculation that determine when it needs to run again.
  • cachedValue: The result returned by the calculation function.
Important: The calculation function should be pure. Avoid side effects inside useMemo.

3. How useMemo Works

React calculates the value when needed and can reuse the cached result on later renders while the dependencies remain unchanged.

Component Renders
→
Check Dependencies
→
Reuse or Recalculate
→
Use Result
Remember: React compares dependencies using Object.is. If a dependency changes, React recalculates the value. In development Strict Mode, the calculation may run more than once to help detect impurities.

4. Example: Calculating a Total

In this example, useMemo calculates the total price from a quantity and price. The total is recalculated when either dependency changes.

Example Code

import { useMemo, useState } from "react";

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

    const total = useMemo(() => {
        return quantity * price;
    }, [quantity, price]);

    return (
        <div>
            <h2>Price Calculator</h2>

            <p>Price: ₹{price}</p>
            <p>Quantity: {quantity}</p>
            <p>Total: ₹{total}</p>

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

export default App;

Expected Output

Price Calculator

Price: ₹100

Quantity: 2

Total: ₹200

After clicking Increase Quantity once:

Quantity: 3

Total: ₹300
Explanation: The total is calculated using quantity multiplied by price. Since both values are dependencies, React recalculates the total when either value changes.

5. Example: Caching an Expensive Calculation

useMemo is useful when a calculation takes significant time and does not need to be repeated when its inputs remain unchanged.

Example Code

import { useMemo, useState } from "react";

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

    let total = 0;

    for (let i = 1; i <= number; i++) {
        total += i;
    }

    return total;
}

function App() {
    const [number, setNumber] = useState(100);
    const [theme, setTheme] = useState("light");

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

    return (
        <div>
            <h2>Calculation Example</h2>

            <p>Number: {number}</p>
            <p>Total: {total}</p>

            <button onClick={() =>
                setNumber(number + 1)
            }>
                Increase Number
            </button>

            <button onClick={() =>
                setTheme(theme === "light"
                    ? "dark"
                    : "light")
            }>
                Change Theme
            </button>

            <p>Theme: {theme}</p>
        </div>
    );
}

export default App;

Expected Output

Number: 100

Total: 5050

After clicking Change Theme:

Theme: dark

The calculation does not need to run again just because the theme changes, since number remains unchanged.

After clicking Increase Number:

Number: 101

Total: 5151
Explanation: The calculation depends only on number. Changing theme causes a re-render, but the cached total can be reused because number has not changed. Updating number causes the calculation to run again.

6. Important Points About useMemo

  • Import useMemo from React.
  • Call Hooks at the top level of a component or custom Hook.
  • Include every reactive value used by the calculation in the dependency array.
  • Keep the calculation pure and free of side effects.
  • useMemo caches a calculated value, not a function.
  • Do not use useMemo automatically for every calculation. Use it when memoization provides a meaningful benefit.
  • React may discard cached values in certain situations, so the cache must not be required for correctness.

7. Difference Between useMemo and useCallback

  • useMemo: Caches the result of a calculation.
  • useCallback: Caches a function definition between renders.
const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

const handleClick = useCallback(() => {
    console.log("Button clicked");
}, []);
Remember: Use useMemo for a calculated value and useCallback when you need to cache a function definition.

8. Practice Tasks

Complete the following exercises:

  1. Create a price calculator using useMemo.
  2. Calculate the total marks of a student using useMemo.
  3. Create a list and calculate its total without repeating the calculation when unrelated state changes.
  4. Create a component with number and theme state variables. Cache a calculation that depends only on number.
  5. Explain the difference between useMemo and useCallback.

Summary

The useMemo Hook caches the result of a calculation between renders and recalculates it when its dependencies change. It can improve performance when a calculation is expensive and its inputs remain unchanged during unrelated renders. The calculation should remain pure, and all reactive dependencies must be included in the dependency array. Unlike useCallback, which caches a function definition, useMemo caches a calculated value. These concepts help developers optimize React applications when memoization is beneficial at CIIT Training Institute.