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

Functional State Updates in React

Learn how to update React state using updater functions, why previous state matters, and how functional updates help build reliable interactive applications for CIIT Training Institute.

1. What Are Functional State Updates?

A functional state update passes a function to a React state setter instead of passing the next value directly. React supplies the previous state value to this function, and the function returns the next state value.

This approach is useful when the next state depends on the previous state, such as increasing a counter or adding another completed lesson.

Syntax
setCount(previousCount => previousCount + 1);

Explanation:

  • setCount requests a state update.
  • previousCount receives the previous queued state value.
  • previousCount + 1 calculates the next count.
  • The returned value becomes the next state value.
Remember: Use a functional update when the next value depends on the previous state.

2. Direct Update vs Functional Update

React lets you pass either a value or an updater function to a state setter. The best choice depends on how the next value is calculated.

DirectUpdate.jsx
setCount(count + 1);

This calculates the next value from the count captured by the current render.

FunctionalUpdate.jsx
setCount(previousCount => previousCount + 1);

This calculates the next value from the previous state supplied by React when processing the updater.

Direct Update Functional Update
setCount(count + 1) setCount(previousCount => previousCount + 1)
Uses the value captured by the current render. Receives the previous queued state value.
Useful when the next value is known or a simple update is appropriate. Useful when the next value depends on the previous state.

3. Counter Example Using Functional Updates

SAMADHAN is completing React lessons at CIIT Training Institute. Each time he clicks the button, the completed lesson count increases by one.

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

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

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

    return (
        <div>
            <h2>Student: SAMADHAN</h2>
            <p>Completed Lessons: {count}</p>

            <button onClick={completeLesson}>
                Complete Lesson
            </button>
        </div>
    );
}

export default LessonCounter;

How it works:

  1. The initial count is 0.
  2. SAMADHAN clicks Complete Lesson.
  3. The updater receives the previous count.
  4. The updater returns the previous count plus one.
  5. React renders the new count.

Expected Browser Output

Initially: Completed Lessons: 0

After one click: Completed Lessons: 1

After two clicks: Completed Lessons: 2

4. Why Multiple Updates Matter

React can batch state updates. If multiple updates use the same state value captured by the current render, each update may calculate the same next value.

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

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

    function increaseThreeTimes() {
        setCount(count + 1);
        setCount(count + 1);
        setCount(count + 1);
    }

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increaseThreeTimes}>
                Increase Three Times
            </button>
        </div>
    );
}

export default Counter;

Expected Result for This Example

Initial count: 0

After clicking once: Count becomes 1, not 3.

All three calls use the same count value from the current render. Each requests the value 1.

Solution: Use functional updates when every update must build on the previous queued value.

5. Increase the Count Three Times Correctly

We can use updater functions to calculate each next value from the result of the preceding queued update.

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

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

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

    return (
        <div>
            <p>Count: {count}</p>

            <button onClick={increaseThreeTimes}>
                Increase Three Times
            </button>
        </div>
    );
}

export default Counter;

Expected Result for This Example

Initial count: 0

After clicking once: Count becomes 3.

Each updater receives the result of the previous queued updater. The sequence is 0 to 1, then 1 to 2, then 2 to 3.

6. Functional Updates in a CIIT Course Dashboard

SAMIKSHA has completed two lessons in a CIIT React course. When she completes another lesson, the dashboard should increase her lesson count using the previous state.

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

function StudentDashboard() {
    const [completedLessons, setCompletedLessons] = useState(2);

    function markLessonComplete() {
        setCompletedLessons(
            previousLessons => previousLessons + 1
        );
    }

    return (
        <div>
            <h2>CIIT Student Dashboard</h2>
            <p>Student: SAMIKSHA</p>
            <p>Completed Lessons: {completedLessons}</p>

            <button onClick={markLessonComplete}>
                Mark Lesson Complete
            </button>
        </div>
    );
}

export default StudentDashboard;

Expected Browser Output

Student: SAMIKSHA

Initially: Completed Lessons: 2

After clicking: Completed Lessons: 3

7. Functional Update Flow Diagram

This diagram shows how React processes functional state updates.

8. Important Rules for Updater Functions

  • Return the next state value from the updater function.
  • Do not mutate the previous state directly.
  • Keep updater functions pure: do not perform side effects inside them.
  • Use functional updates when the next value depends on previous state.
  • Do not expect a setter to update the current render's variable immediately.
CorrectUpdater.jsx
setCount(previousCount => previousCount + 1);
Important: React may invoke updater functions more than once in development Strict Mode to help detect accidental side effects. Keep updater functions pure.

9. Common Mistakes

Mistake 1: Repeating a direct update

May Not Produce Three Increments
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);

Correct approach:

Functional Updates
setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);

Mistake 2: Mutating state

Do not modify objects or arrays in place. Return a new object or array when updating structured state.

Mistake 3: Performing side effects in an updater

Keep updater functions limited to calculating and returning the next state value.

10. Practice Exercises

  1. Create a counter that increases three times on one click.
  2. Start SAMADHAN's completed lesson count at 4 and increment it.
  3. Update SAMIKSHA's course progress using a functional updater.
  4. Create a counter that decreases using previous state.
  5. Explain why three direct updates can produce only one increment.
  6. Explain when a functional state update is useful.
Practice Tip: Run the examples in your React project to observe how direct updates and functional updates behave.

11. Quick Revision

  • Functional updates pass a function to a state setter.
  • React supplies the previous state value to the updater.
  • The updater returns the next state value.
  • Functional updates are useful when updates depend on previous state.
  • Updater functions should be pure.

Summary

Functional state updates help calculate the next state from the previous state. They are particularly useful when multiple updates are queued or when the next value depends on the latest state. For example, setCount(previousCount => previousCount + 1) calculates an increment using the previous value supplied by React. Always keep updater functions pure and return the next state instead of mutating the existing state.