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

useReducer Hook

Learn how to manage component state using the useReducer Hook, reducer functions, actions, and dispatch in React.

1. What Is the useReducer Hook?

The useReducer Hook is a built-in React Hook used to manage state through a reducer function. It is useful when state updates involve multiple actions or more complex logic.

Instead of updating state directly through a setter function, a component dispatches an action. The reducer receives the current state and the action, then returns the next state.

Remember: useReducer is an alternative to useState when state management becomes more structured or complex.

2. Syntax of useReducer

The basic syntax is:

const [state, dispatch] = useReducer(
    reducer,
    initialState
);
  • reducer: A function that calculates the next state.
  • initialState: The initial state value.
  • state: The current state returned by the Hook.
  • dispatch: The function used to send an action to the reducer.

3. How useReducer Works

The component dispatches an action when a user performs an operation. React passes the current state and action to the reducer and uses the returned state for the next render.

User Action
→
dispatch()
→
Reducer
→
New State
Important: A reducer should be a pure function. It should calculate and return the next state without modifying the existing state or performing side effects.

4. Example: Counter Using useReducer

In this example, the counter supports three actions: increase, decrease, and reset.

Example Code

import { useReducer } from "react";

function reducer(state, action) {
    switch (action.type) {
        case "increase":
            return state + 1;

        case "decrease":
            return state - 1;

        case "reset":
            return 0;

        default:
            return state;
    }
}

function App() {
    const [count, dispatch] = useReducer(
        reducer,
        0
    );

    return (
        <div>
            <h2>Counter Application</h2>

            <p>Count: {count}</p>

            <button onClick={() =>
                dispatch({ type: "increase" })
            }>
                Increase
            </button>

            <button onClick={() =>
                dispatch({ type: "decrease" })
            }>
                Decrease
            </button>

            <button onClick={() =>
                dispatch({ type: "reset" })
            }>
                Reset
            </button>
        </div>
    );
}

export default App;

Expected Output

Counter Application

Initial value: Count: 0

After clicking Increase: Count: 1

After clicking Increase again: Count: 2

After clicking Decrease: Count: 1

After clicking Reset: Count: 0

Explanation: The reducer checks action.type using a switch statement. The dispatch function sends an action, and the reducer returns the new counter value.

5. Managing Object State with useReducer

The useReducer Hook can also manage objects containing multiple related values, such as a student's name and course.

Example Code

import { useReducer } from "react";

const initialState = {
    name: "Samadhan",
    course: "React"
};

function reducer(state, action) {
    switch (action.type) {
        case "changeName":
            return {
                ...state,
                name: "Samiksha"
            };

        case "changeCourse":
            return {
                ...state,
                course: "Angular"
            };

        default:
            return state;
    }
}

function App() {
    const [student, dispatch] = useReducer(
        reducer,
        initialState
    );

    return (
        <div>
            <h2>Student Information</h2>

            <p>Name: {student.name}</p>
            <p>Course: {student.course}</p>

            <button onClick={() =>
                dispatch({ type: "changeName" })
            }>
                Change Name
            </button>

            <button onClick={() =>
                dispatch({ type: "changeCourse" })
            }>
                Change Course
            </button>
        </div>
    );
}

export default App;

Expected Output

Initially:

Name: Samadhan
Course: React

After clicking Change Name:

Name: Samiksha

After clicking Change Course:

Course: Angular
Explanation: Each action updates a specific property. The spread operator ...state preserves the other properties while returning a new object.

6. Difference Between useState and useReducer

  • useState: Suitable for simple state values and straightforward updates.
  • useReducer: Useful when multiple actions determine how state changes.
  • useState: Updates state through a setter function.
  • useReducer: Dispatches actions to a reducer function.
  • Both Hooks can update state and cause React to re-render the component when the state changes.
Remember: useReducer is not always better than useState. Choose the Hook that makes your component's state logic easiest to understand and maintain.

7. Important Points About useReducer

  • Import useReducer from React.
  • The reducer receives the current state and an action.
  • Dispatch sends an action to the reducer.
  • The reducer must return the next state.
  • Avoid directly modifying objects or arrays in state.
  • Use a default case to handle unexpected action types.
  • Keep side effects outside the reducer function.

8. Practice Tasks

Complete the following exercises:

  1. Create a counter using useReducer with Increase and Decrease actions.
  2. Add a Reset action to the counter.
  3. Create a reducer that changes a student's name.
  4. Manage student name and course using an object state.
  5. Explain the difference between dispatch and a useState setter function.
  6. Write a reducer with a default case for unknown actions.

Summary

The useReducer Hook manages React component state using a reducer function and dispatched actions. The reducer receives the current state and an action, then returns the next state without modifying the existing state directly. It is useful for counters, forms, and components with multiple related state transitions. Understanding reducers, actions, and dispatch helps developers organize state logic and build maintainable React applications at CIIT Training Institute.