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 With Arrays

Learn how to store arrays in React state, display list items, add new items, remove items, update array values, and follow immutable state update practices.

1. What Is State With Arrays?

An array is used to store multiple values in a single variable. In React, we can store an array in state when we need to manage a list of students, courses, tasks, or products.

For example, CIIT Training Institute can maintain a list of students enrolled in a React course.

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

This array contains three student names. Using useState(), we can store the array in React state and update it when the list changes.

2. React Array State — Visual Diagram

The following diagram explains how React manages an array and updates the user interface when the array changes.

React State students
↓
Array Items
SAMADHAN SAMIKSHA PRADNYA
↓
Array Operation

Add / Remove / Update

↓
Updated UI

React renders the updated list

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

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

    return (
        <div>
            <h2>CIIT Student List</h2>
            <p>Total Students: {students.length}</p>
        </div>
    );
}

export default StudentList;
Remember: students stores the current array, setStudents updates it, and students.length returns the number of items.

3. Creating an Array Using useState()

The useState() Hook allows a functional component to store an array as state.

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

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

    return (
        <div>
            <h2>CIIT Training Institute</h2>
            <p>Total Students: {students.length}</p>
        </div>
    );
}

export default StudentArray;

Understanding the Code

  • useState() initializes the state with an array.
  • students contains the current array.
  • setStudents is used to update the state.
  • students.length gives the array's item count.

Expected Browser Output

Browser Output

CIIT Training Institute

Total Students: 3

4. Displaying Array Items Using map()

The map() method processes every array item and returns a new array. In React, it is commonly used to render a list of JSX elements.

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

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

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

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

export default DisplayStudents;

How Does map() Work?

  1. React reads the array of students.
  2. map() processes each student name.
  3. Each name is placed inside an li element.
  4. React displays the resulting list in the browser.

Expected Browser Output

Browser Output

CIIT Student List

  • SAMADHAN
  • SAMIKSHA
  • PRADNYA
Important: Every rendered list item should have a stable, unique key. In a real application, prefer a student ID rather than a name if names may repeat or change.

5. Adding an Item to an Array

We can add a new item by creating a new array with the spread operator. The existing items are copied into the new array, followed by the new student.

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

function AddStudent() {
    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 AddStudent;

Explanation

  • addStudent() runs when the button is clicked.
  • previousStudents represents the previous state supplied by React.
  • ...previousStudents copies the existing items.
  • "ROHAN" is added at the end of the new array.
  • setStudents() schedules the state update.
Before Clicking SAMADHAN SAMIKSHA PRADNYA Total: 3
After Clicking SAMADHAN SAMIKSHA PRADNYA ROHAN Total: 4
Remember: The functional updater form is useful when the next state depends on the previous state.

6. Removing an Item Using filter()

The filter() method creates a new array containing only the items that satisfy a condition. We can use it to remove a student from a list.

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

function RemoveStudent() {
    const [students, setStudents] = useState([
        { id: 1, name: "SAMADHAN" },
        { id: 2, name: "SAMIKSHA" },
        { id: 3, name: "PRADNYA" }
    ]);

    function removeStudent(studentId) {
        setStudents((previousStudents) =>
            previousStudents.filter(
                (student) => student.id !== studentId
            )
        );
    }

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

            {students.map((student) => (
                <div key={student.id} className="student-row">
                    <span>{student.name}</span>

                    <button
                        onClick={() => removeStudent(student.id)}
                    >
                        Remove
                    </button>
                </div>
            ))}
        </div>
    );
}

export default RemoveStudent;

How Does It Work?

  1. Each student has a unique id.
  2. Clicking Remove passes that student's ID to the function.
  3. filter() keeps all students whose ID does not match the selected ID.
  4. React renders the new array without the removed student.
Before SAMADHAN SAMIKSHA PRADNYA
After Removing SAMIKSHA SAMADHAN PRADNYA

7. Updating an Item Using map()

We can use map() to update a specific item while keeping the other items unchanged. For this example, each student has a unique ID.

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

function UpdateStudent() {
    const [students, setStudents] = useState([
        { id: 1, name: "SAMADHAN" },
        { id: 2, name: "SAMIKSHA" },
        { id: 3, name: "PRADNYA" }
    ]);

    function updateStudent(studentId) {
        setStudents((previousStudents) =>
            previousStudents.map((student) =>
                student.id === studentId
                    ? {
                        ...student,
                        name: student.name + " - React Student"
                    }
                    : student
            )
        );
    }

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

            {students.map((student) => (
                <div key={student.id} className="student-row">
                    <span>{student.name}</span>

                    <button
                        onClick={() => updateStudent(student.id)}
                    >
                        Update
                    </button>
                </div>
            ))}
        </div>
    );
}

export default UpdateStudent;

Explanation

  • map() checks each student in the array.
  • If the ID matches, a new student object is created.
  • The spread operator preserves the existing properties.
  • If the ID does not match, the original student object is returned unchanged.
Example Output After Updating SAMADHAN
  • SAMADHAN - React Student
  • SAMIKSHA
  • PRADNYA
Important: This example appends the text each time Update is clicked. A real application might instead replace the name with a value entered by the user.

8. Why Should We Avoid Mutating Arrays?

React state should be treated as read-only. Directly changing an existing state array can cause confusing behavior and prevents React from reliably detecting changes by reference.

Avoid This
students.push("ROHAN");
setStudents(students);

push() modifies the existing array.

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

The spread operator creates a new array.

Other useful immutable operations:
  • map() — transform or update items.
  • filter() — remove items based on a condition.
  • [...array, newItem] — append an item.
  • [newItem, ...array] — add an item at the beginning.
  • slice() — create a shallow copy of part of an array.

9. Common Mistakes

Modifying State with push()

Avoid:

students.push("ROHAN");

Use:

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

Removing Items with splice()

Avoid:

students.splice(1, 1);

Use:

setStudents(previous =>
    previous.filter(student => student.id !== 2)
);

Forgetting the key Attribute

Avoid:

students.map(student => <li>{student.name}</li>)

Use:

students.map(student => <li key={student.id}>{student.name}</li>)

Updating the Wrong Item

Use a unique ID to identify the item you want to update or remove. Array indexes can change when items are inserted, deleted, or reordered.

10. Practice Questions

  1. Create a React state array containing SAMADHAN, SAMIKSHA, and PRADNYA.
  2. Display all student names using map().
  3. Add a new student when a button is clicked.
  4. Remove a selected student using filter().
  5. Update one student's name using map().
  6. Display the total number of students using length.
  7. Explain why directly using push() on a state array should be avoided.

Summary

React array state allows us to manage lists of students, courses, tasks, and products dynamically. The useState() Hook stores the array, map() helps display and update items, and filter() helps remove items. The spread operator creates a new array when adding elements. Always avoid directly mutating state arrays and use stable, unique keys when rendering lists. These practices help keep React state updates predictable and the user interface consistent.