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

Memoizing Components with React.memo

React applications are built using reusable components. Whenever a component's state changes or its parent renders again, React may execute that component to calculate the updated user interface. Sometimes a child component receives exactly the same props as before, so rendering it again may perform unnecessary work.

React.memo is a React API that lets you create a memoized version of a component. When its props remain unchanged according to the default comparison, React can skip rendering that component during a parent update.

Learning objective: Understand React.memo, learn how props are compared, identify suitable components for memoization, and use React.memo in practical React applications.

1. What Is Memoization?

Memoization is an optimization technique that reuses a previously calculated result when the relevant inputs have not changed. Instead of repeating the same work, a program can reuse the previous result when appropriate.

In React, React.memo applies this idea to function components. It allows React to reuse the previous rendered result for a component when its props have not changed, instead of rendering the component again because its parent rendered.

Parent Renders Again
↓
React Compares Child Props
↓
Props Unchanged?
↓
Skip Child Render When Eligible
React.memo is a performance optimization, not a requirement for every component. React may still render a memoized component when its own state or a context value it consumes changes.

2. Syntax of React.memo

React.memo receives a component and returns a memoized component. You can import memo from React and wrap the function component.

Basic Syntax
import { memo } from "react";

const MyComponent = memo(function MyComponent(props) {
    return <h2>Hello, {props.name}</h2>;
});

export default MyComponent;

In this syntax:

  • memo: The React API used to memoize a component.
  • MyComponent: The function component being optimized.
  • props: The data received by the component.
  • export default: Makes the component available for import elsewhere.

3. Example Without React.memo

First, create a parent component with a counter and a child component displaying a student's name. Clicking the counter button changes the parent's state, causing the parent to render again.

StudentApp.jsx — Without memo
import { useState } from "react";

function StudentCard({ name }) {
    console.log("StudentCard rendered");

    return (
        <div>
            <h3>Student Name: {name}</h3>
            <p>Welcome to CIIT Training Institute.

How It Works

  1. StudentApp renders and displays Counter: 0.
  2. StudentCard displays the name Samadhan.
  3. The user clicks Increase Counter.
  4. setCount updates the parent's state.
  5. StudentApp renders again with the updated count.
  6. StudentCard can render again even though its name prop is unchanged.

Expected Console Behavior

Initial render:

StudentApp rendered

StudentCard rendered

After a counter click:

StudentApp rendered

StudentCard rendered

Development Strict Mode can cause extra render calls while React checks components for unintended side effects. Therefore, the number of console messages may be higher in development.

4. Example With React.memo

Now import memo from React and wrap StudentCard. The name prop is a string and remains unchanged when only the counter updates. React.memo can therefore skip rendering StudentCard during that parent update.

StudentApp.jsx — With memo
import { memo, useState } from "react";

const StudentCard = memo(function StudentCard({ name }) {
    console.log("StudentCard rendered");

    return (
        <div>
            <h3>Student Name: {name}</h3>
            <p>Welcome to CIIT Training Institute.</p>
        </div>
    );
});

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

    console.log("StudentApp rendered");

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

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

            <StudentCard name="Samadhan" />
        </div>
    );
}

export default StudentApp;

Expected Behavior

Counter Changes
↓
StudentApp Renders Again
↓
React.memo Checks name
↓
Same Name: StudentCard Can Be Skipped

Initial render: StudentApp and StudentCard render.

After clicking Increase Counter: StudentApp renders again, but StudentCard can skip rendering.

The counter updates normally, and the student's name remains visible.

5. How Does React.memo Compare Props?

By default, React.memo compares each prop in the previous render with the corresponding prop in the next render using Object.is. If all props compare equal, React can skip rendering the memoized component when the update comes from its parent.

Prop Type Example Comparison Behavior
String "Samadhan" Same string value compares equal.
Number 25 Same number compares equal.
Boolean true Same boolean value compares equal.
Object {`{ name: "Samadhan" }`} Different object references compare unequal, even if their contents look the same.
Function onClick handler A newly created function generally has a different reference.
React.memo performs a shallow prop comparison by default. It does not recursively compare every property inside nested objects.

6. Problem: New Object Props

Consider a parent that creates a new object every time it renders. Even when the object contains the same student name, its reference is new. React.memo therefore treats that prop as changed.

StudentObject.jsx
import { memo, useState } from "react";

const StudentCard = memo(function StudentCard({ student }) {
    console.log("StudentCard rendered");

    return <h3>Student: {student.name}</h3>;
});

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

    const student = { name: "Samiksha" };

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

            <StudentCard student={student} />
        </div>
    );
}

export default StudentObject;

Why Does the Child Render Again?

  1. The parent renders and creates a student object.
  2. The counter changes and the parent renders again.
  3. A new student object is created.
  4. The new object reference differs from the previous reference.
  5. React.memo detects a changed prop, so it cannot skip the child based on prop equality.

Improved Example: Pass a Primitive Prop

StudentObject.jsx — Improved
import { memo, useState } from "react";

const StudentCard = memo(function StudentCard({ name }) {
    console.log("StudentCard rendered");

    return <h3>Student: {name}</h3>;
});

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

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

            <StudentCard name="Samiksha" />
        </div>
    );
}

export default StudentObject;

Here, the name prop remains the same string. When only the counter changes, React.memo can skip the child render because the prop has not changed.

7. Using React.memo with Multiple Props

A memoized component can receive multiple props. React compares each prop separately. If any prop changes, the component will generally render again in response to the parent update.

StudentProfile.jsx
import { memo, useState } from "react";

const StudentProfile = memo(function StudentProfile({ name, course }) {
    console.log("StudentProfile rendered");

    return (
        <div>
            <h3>{name}</h3>
            <p>Course: {course}</p>
        </div>
    );
});

function StudentApp() {
    const [count, setCount] = useState(0);
    const [course, setCourse] = useState("React");

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

            <button onClick={() => setCourse("Node.js")}>
                Change Course
            </button>

            <StudentProfile
                name="Samadhan"
                course={course}
            />
        </div>
    );
}

export default StudentApp;

Expected Behavior

Click Counter: StudentProfile can skip rendering because its props remain unchanged.

Click Change Course: StudentProfile renders again because the course prop changes.

The displayed course changes from React to Node.js.

8. When Should You Use React.memo?

  • When a component renders frequently with the same props.
  • When rendering the component involves meaningful work.
  • When a parent updates for reasons unrelated to the child.
  • When profiling shows that repeated child renders are a bottleneck.
  • When the component receives stable primitive props or intentionally stable references.

9. When Should You Avoid React.memo?

  • When the component is very small and inexpensive to render.
  • When its props change on almost every render.
  • When memoization makes the code unnecessarily complicated.
  • When no measurable performance benefit is expected.
React.memo does not prevent updates caused by a component's own state or the context values it consumes. It also does not guarantee that React will never render the component again. Treat it as a performance optimization rather than a correctness mechanism.

10. Custom Comparison Function

React.memo also accepts an optional second argument: a comparison function. It receives the previous props and next props. Return true when the component can reuse its previous rendered result, and false when it should render again.

StudentCard.jsx
import { memo } from "react";

const StudentCard = memo(
    function StudentCard({ student }) {
        return <h3>Student: {student.name}</h3>;
    },
    (previousProps, nextProps) => {
        return previousProps.student.name ===
               nextProps.student.name;
    }
);

export default StudentCard;

In this example, the comparison function checks only the student's name. If the name remains the same, it returns true and allows React to skip rendering based on this comparison.

Custom comparison functions must compare every prop that affects the rendered output, including function props. Ignoring a changed callback can preserve a component with outdated behavior. Custom comparisons can also cost more than rendering, so use them carefully.

11. Common Mistakes

  1. Assuming React.memo stops all component renders.
  2. Passing newly created objects and functions to memoized components without considering their references.
  3. Using memoization on every component without measuring performance.
  4. Assuming equal object contents always mean equal object references.
  5. Using a custom comparison function that ignores important props.
  6. Expecting React.memo to prevent updates from local state or consumed context.

12. Practice Tasks

Task 1: Basic Memoization

Create a Parent component with a counter and a StudentCard child. Observe the console before and after wrapping StudentCard with React.memo.

Task 2: Multiple Props

Create a memoized profile component that accepts name, course, and city. Change one prop at a time and observe which updates cause the child to render.

Task 3: Object References

Pass an object to a memoized child. Change the parent's counter and explain why a newly created object can cause another render.

Task 4: Custom Comparison

Create a comparison function for a student profile. Ensure that every prop affecting the UI is compared correctly.

Task 5: Explain the Concept

In your own words, explain memoization, shallow prop comparison, and two situations in which React.memo may improve performance.

Summary

React.memo creates a memoized version of a function component and can skip rendering it when its props compare equal using React's default shallow comparison. It is useful when a child repeatedly receives unchanged props while its parent renders for another reason. Newly created object and function references can prevent the optimization, while changed props, local state, and consumed context can still lead to renders. A custom comparison function is available but must be written carefully. At CIIT Training Institute, practice memoization with parent-child components and use profiling to confirm that an optimization provides a real benefit.