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

State Immutability

Learn why React state should be treated as read-only, understand mutable and immutable updates, and use the spread operator, map(), and filter() to update state safely.

1. What Is State Immutability?

Immutability means creating a new value instead of directly modifying an existing value. In React, we should treat state as read-only and use the state setter to provide an updated value.

For example, if CIIT Training Institute maintains a list of students, we should create a new array when adding or removing a student instead of modifying the existing state array.

Example:
const students = [
    "SAMADHAN",
    "SAMIKSHA",
    "PRADNYA"
];

// Create a new array
const updatedStudents = [
    ...students,
    "ROHAN"
];

The original array remains unchanged. The new array contains the original students and the additional student.

2. Mutable vs Immutable Updates

A mutable update modifies an existing array or object. An immutable update creates a new array or object containing the required changes.

Mutable Update — Avoid
Original Array students
↓
students.push("ROHAN")
↓
Same Array Modified
Immutable Update — Preferred
Original Array students
↓
[...students, "ROHAN"]
↓
New Array Created
Remember: React state should be treated as read-only. When state changes, create a new array or object and pass it to the state setter.

3. Directly Mutating State

Mutating state means directly changing an existing array or object stored in React state. This should be avoided because the reference may remain unchanged, and React may skip the expected re-render when the same value is passed back.

IncorrectUpdate.jsx JSX
import { useState } from "react";

function StudentList() {
    const [students, setStudents] = useState([
        "SAMADHAN",
        "SAMIKSHA",
        "PRADNYA"
    ]);

    function addStudent() {
        students.push("ROHAN");
        setStudents(students);
    }

    return (
        <div>
            <h2>CIIT Student List</h2>

            <button onClick={addStudent}>
                Add Student
            </button>

            <ul>
                {students.map((student, index) => (
                    <li key={`${student}-${index}`}>
                        {student}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default StudentList;
Why is this incorrect?
  • push() modifies the existing array.
  • The original state array is changed directly.
  • The same array reference is passed to the setter.
  • React may skip the expected re-render because the reference has not changed.

4. Updating Arrays Immutably

The spread operator creates a new array containing the existing items. We can add a new item without modifying the original state array.

ImmutableArrayUpdate.jsx JSX
import { useState } from "react";

function StudentList() {
    const [students, setStudents] = useState([
        "SAMADHAN",
        "SAMIKSHA",
        "PRADNYA"
    ]);

    function addStudent() {
        setStudents((previousStudents) => [
            ...previousStudents,
            "ROHAN"
        ]);
    }

    return (
        <div>
            <h2>CIIT Student List</h2>

            <button onClick={addStudent}>
                Add Student
            </button>

            <ul>
                {students.map((student, index) => (
                    <li key={`${student}-${index}`}>
                        {student}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default StudentList;

How Does It Work?

  1. The button calls the addStudent() function.
  2. The functional updater receives the previous state.
  3. The spread operator copies the existing array items.
  4. The new student is added to the new array.
  5. React receives the new state and updates the interface.

Expected Browser Output

Browser Output After Clicking Add Student
  • SAMADHAN
  • SAMIKSHA
  • PRADNYA
  • ROHAN

5. Updating Objects Immutably

React state can also contain objects. We should create a new object when updating a property instead of directly changing a property of the existing state object.

Incorrect
student.name = "SAMIKSHA";
setStudent(student);

This changes the existing object directly.

Correct
setStudent(previous => ({
    ...previous,
    name: "SAMIKSHA"
}));

This creates a new object with the updated name.

StudentObject.jsx JSX
import { useState } from "react";

function StudentObject() {
    const [student, setStudent] = useState({
        name: "SAMADHAN",
        course: "React JS",
        institute: "CIIT Training Institute"
    });

    function updateStudent() {
        setStudent((previousStudent) => ({
            ...previousStudent,
            name: "SAMIKSHA"
        }));
    }

    return (
        <div>
            <h2>Student Details</h2>
            <p>Name: {student.name}</p>
            <p>Course: {student.course}</p>
            <p>Institute: {student.institute}</p>

            <button onClick={updateStudent}>
                Update Student Name
            </button>
        </div>
    );
}

export default StudentObject;
Expected Browser Output After Clicking

Name: SAMIKSHA

Course: React JS

Institute: CIIT Training Institute

Important: The spread operator creates a shallow copy. If an object contains nested objects, copy each level that needs updating.

6. Using map() and filter() Immutably

The map() and filter() methods return new arrays. They are useful for updating or removing items without modifying the original array.

Using map() to Update an Item

MapUpdate.jsx JSX
setStudents((previousStudents) =>
    previousStudents.map((student) =>
        student.id === 1
            ? { ...student, name: "SAMADHAN - React Student" }
            : student
    )
);

The matching student is replaced with a new object. All other students remain unchanged.

Using filter() to Remove an Item

FilterRemove.jsx JSX
setStudents((previousStudents) =>
    previousStudents.filter(
        (student) => student.id !== 2
    )
);

The returned array contains every student except the student whose ID is 2.

Remember:
  • map() creates a transformed array.
  • filter() creates an array containing matching items.
  • Neither method mutates the original array when used in these examples.

7. Understanding the Spread Operator

The spread operator (...) expands the items of an array or the properties of an object into a new array or object.

SpreadOperator.jsx JSX
const originalStudents = [
    "SAMADHAN",
    "SAMIKSHA"
];

const updatedStudents = [
    ...originalStudents,
    "PRADNYA"
];

console.log(originalStudents);
console.log(updatedStudents);
Console Output

originalStudents:

["SAMADHAN", "SAMIKSHA"]

updatedStudents:

["SAMADHAN", "SAMIKSHA", "PRADNYA"]
Key Point: Creating a new array with the spread operator does not change the original array. However, this is a shallow copy, so nested objects are not automatically cloned.

8. Common Mistakes

Using push() to Modify State

Avoid:

students.push("ROHAN");

Use:

setStudents(previous => [...previous, "ROHAN"]);

Changing an Object Property Directly

Avoid:

student.name = "SAMIKSHA";

Use:

setStudent(previous => ({
    ...previous,
    name: "SAMIKSHA"
}));

Updating State Using a Stale Value

When the next state depends on the previous state, prefer a functional updater.

Recommended:

setCount(previousCount => previousCount + 1);

Assuming Spread Makes a Deep Copy

The spread operator copies only one level. When updating nested state, create new objects at every level that needs to change.

9. Practice Questions

  1. Explain state immutability in React.
  2. Why should we avoid using push() directly on a state array?
  3. Create a new array by adding a student using the spread operator.
  4. Remove a student using filter() without mutating the original array.
  5. Update a student's name using map().
  6. Update a student object using the spread operator.
  7. Explain the difference between a shallow copy and a deep copy.

Summary

State immutability means treating React state as read-only and creating new arrays or objects whenever an update is required. The spread operator helps copy existing values, map() is useful for updating array items, and filter() helps remove items. Avoid directly modifying state with methods such as push() or by changing object properties. When the next value depends on the previous state, use a functional state updater. These practices help make React applications more predictable and easier to maintain.