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

Updating State in React

Learn how to update React state using setter functions, understand why direct state mutation is incorrect, and explore practical examples using CIIT Training Institute's student and course scenarios.

1. What Does Updating State Mean?

Updating state means requesting a new value for information stored in a React component. When the value changes, React can render the component again to display the updated data.

For example, SAMADHAN has completed two React courses. After completing another course, the dashboard should display three completed courses.

UpdatingState.jsx
import { useState } from "react";

function StudentProgress() {
    const [completedCourses, setCompletedCourses] = useState(2);

    function completeCourse() {
        setCompletedCourses(completedCourses + 1);
    }

    return (
        <div>
            <h2>Student: SAMADHAN</h2>
            <p>Completed Courses: {completedCourses}</p>

            <button onClick={completeCourse}>
                Complete Another Course
            </button>
        </div>
    );
}

export default StudentProgress;

Expected Browser Output

Student: SAMADHAN

Initially: Completed Courses: 2

After clicking once: Completed Courses: 3

Remember: Use the setter function to request a state update. Do not directly assign a new value to the state variable.

2. Updating State with a Setter Function

The setter function returned by useState requests an update to the state value. You can pass the next value directly when you already know what that value should be.

DirectValueUpdate.jsx
import { useState } from "react";

function StudentName() {
    const [name, setName] = useState("SAMIKSHA");

    function changeName() {
        setName("PRADNYA");
    }

    return (
        <div>
            <h2>Student Name: {name}</h2>

            <button onClick={changeName}>
                Change Student Name
            </button>
        </div>
    );
}

export default StudentName;

Explanation:

  • The initial name is SAMIKSHA.
  • Clicking the button calls changeName.
  • setName("PRADNYA") requests the new name.
  • React renders the updated name.

Expected Browser Output

Before clicking: Student Name: SAMIKSHA

After clicking: Student Name: PRADNYA

3. Updating Number State

Number state is useful for counters, course progress, attendance totals, and the number of completed lessons.

CourseCounter.jsx
import { useState } from "react";

function CourseCounter() {
    const [lessonsCompleted, setLessonsCompleted] = useState(0);

    return (
        <div>
            <h2>PRADNYA's Course Progress</h2>
            <p>Lessons Completed: {lessonsCompleted}</p>

            <button
                onClick={() =>
                    setLessonsCompleted(lessonsCompleted + 1)
                }
            >
                Complete Lesson
            </button>
        </div>
    );
}

export default CourseCounter;

Expected Browser Output

Initially: Lessons Completed: 0

After one click: Lessons Completed: 1

After two clicks: Lessons Completed: 2

Each click requests an increment of the lesson count. React then displays the current value in the component.

4. Updating String State

String state can store names, course titles, messages, selected categories, and other text values.

CourseStatus.jsx
import { useState } from "react";

function CourseStatus() {
    const [status, setStatus] = useState("In Progress");

    function completeCourse() {
        setStatus("Completed");
    }

    return (
        <div>
            <h2>Student: SAMADHAN</h2>
            <p>React Course Status: {status}</p>

            <button onClick={completeCourse}>
                Complete Course
            </button>
        </div>
    );
}

export default CourseStatus;

Expected Browser Output

Initially: React Course Status: In Progress

After clicking: React Course Status: Completed

5. Updating Boolean State

Boolean state stores either true or false. It is useful for showing or hiding content, opening menus, and enabling or disabling interface elements.

StudentMessage.jsx
import { useState } from "react";

function StudentMessage() {
    const [isVisible, setIsVisible] = useState(false);

    function toggleMessage() {
        setIsVisible(!isVisible);
    }

    return (
        <div>
            <h2>Welcome, SAMIKSHA!</h2>

            <button onClick={toggleMessage}>
                {isVisible ? "Hide Message" : "Show Message"}
            </button>

            {isVisible && (
                <p>Welcome to CIIT Training Institute!</p>
            )}
        </div>
    );
}

export default StudentMessage;

Expected Browser Output

Initially: The welcome message is hidden.

After clicking Show Message: The welcome message appears.

After clicking Hide Message: The message disappears.

6. Direct Value vs Functional Update

React supports two common ways to request a state update: passing a next value or passing an updater function.

Method Example When to Use
Direct value setCount(10) When the next value is already known.
Calculate from current render setCount(count + 1) For a straightforward update based on the current value.
Functional update setCount(previousCount => previousCount + 1) When the next value depends on the previous state.
FunctionalUpdate.jsx
import { useState } from "react";

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

    function completeLesson() {
        setCount(previousCount => previousCount + 1);
    }

    return (
        <div>
            <h2>SAMADHAN's Completed Lessons: {count}</h2>
            <button onClick={completeLesson}>
                Complete Lesson
            </button>
        </div>
    );
}

export default CourseCounter;
Important: Functional updates are especially useful when multiple updates depend on the latest queued state value.

7. State Update Flow Diagram

The following diagram summarizes how a state update changes what the user sees.

8. Common State Updating Mistakes

Mistake 1: Direct assignment

Incorrect
count = count + 1;

This assignment does not request a React state update. Use the setter function.

Correct
setCount(count + 1);

Mistake 2: Expecting the value to change immediately

Example
setCount(count + 1);
console.log(count); // Value from the current render

The console statement reads the state value belonging to the current render. The setter requests an update for a subsequent render.

Mistake 3: Mutating an object or array

When updating objects and arrays, create a new value instead of directly modifying the existing state. We will study this in the upcoming lessons.

9. Practice Exercises

Practice these examples for the CIIT React tutorial:

  1. Create a counter that starts at 5 and increases on each click.
  2. Change the student name from SAMADHAN to SAMIKSHA.
  3. Display a welcome message for PRADNYA when a button is clicked.
  4. Change a course status from In Progress to Completed.
  5. Create a Boolean state to show or hide course details.
  6. Explain the difference between direct and functional updates.
Practice Tip: These code examples are educational snippets. Run them in your React application to test the actual interactions.

10. Quick Revision

  • State updates are requested through setter functions.
  • State can store strings, numbers, Boolean values, objects, and arrays.
  • Direct assignment does not request a React state update.
  • Functional updates calculate the next value from the previous state.
  • React renders the component using its updated state.
  • State makes interactive course dashboards and forms possible.

Summary

Updating state is essential for building interactive React applications. A setter function requests a new state value, and React can render the component with that updated value. You can update numbers, strings, and Boolean values, while functional updates are useful when the next value depends on the previous state. In the next lesson, we will learn how functional state updates work in detail.