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

Async Operations with Redux Toolkit

Learn how to handle API requests, loading states, successful responses, and errors using Redux Toolkit.

1. What Are Asynchronous Operations?

An asynchronous operation is a task that takes time to complete without blocking the rest of the application. Examples include fetching student details from an API, submitting a form, and loading course information from a server.

In a React application, an API request may take several seconds. During that time, the application should be able to show a loading message, display the result when the request succeeds, or show an error when the request fails.

Example: Student Dashboard

When a student opens the dashboard, the application requests student information from an API. Redux Toolkit can manage the request lifecycle and keep the resulting data in the store.

API Request Flow

React Component
↓
Dispatch Async Action
↓
Send API Request
↓
Success or Failure
↓
Update Redux State
↓
Update React UI

2. What Is createAsyncThunk()?

createAsyncThunk() is a Redux Toolkit utility used to create action creators for asynchronous operations. It simplifies handling the lifecycle of an operation such as an API request.

For each asynchronous operation, Redux Toolkit generates three lifecycle actions:

Pending

Dispatched when the asynchronous operation starts. The application can set its loading state to true.

fetchStudents.pending

Fulfilled

Dispatched when the operation completes successfully. The application can save the returned data in the store.

fetchStudents.fulfilled

Rejected

Dispatched when the operation fails. The application can save an error message in the store.

fetchStudents.rejected
Remember: createAsyncThunk() creates the lifecycle action creators and thunk action creator. You handle the lifecycle actions in createSlice() using extraReducers.

3. Install Required Packages

If you are starting a new React project, install Redux Toolkit and React-Redux.

npm install @reduxjs/toolkit react-redux

This lesson uses a sample public API to demonstrate fetching data. You can replace the URL with your own student API endpoint.

4. Create an Async Thunk

First, create an asynchronous thunk that requests student data from an API. The example below uses JSONPlaceholder to demonstrate the request lifecycle.

File: studentSlice.js

import {
    createSlice,
    createAsyncThunk
} from "@reduxjs/toolkit";

export const fetchStudents = createAsyncThunk(
    "students/fetchStudents",
    async (_, { rejectWithValue }) => {
        try {
            const response = await fetch(
                "https://jsonplace.typicode.com/users"
            );

            if (!response.ok) {
                throw new Error("Failed to fetch students");
            }

            return await response.json();
        } catch (error) {
            return rejectWithValue(
                error.message || "Something went wrong"
            );
        }
    }
);

Explanation

createAsyncThunk() Creates the asynchronous thunk action creator.
fetch() Sends the HTTP request to the API.
await Waits for the asynchronous operation to complete.
response.ok Checks whether the HTTP status is successful.
rejectWithValue() Provides a custom error payload for a rejected action.
JSONPlaceholder returns sample user objects rather than actual student records. It is useful for learning and testing API integration.

5. Create the Slice with Loading and Error States

Now define the initial state and handle the pending, fulfilled, and rejected actions inside extraReducers.

File: studentSlice.js (continued)

const studentSlice = createSlice({
    name: "students",

    initialState: {
        data: [],
        loading: false,
        error: null
    },

    reducers: {},

    extraReducers: (builder) => {
        builder
            .addCase(fetchStudents.pending, (state) => {
                state.loading = true;
                state.error = null;
            })

            .addCase(fetchStudents.fulfilled, (state, action) => {
                state.loading = false;
                state.data = action.payload;
            })

            .addCase(fetchStudents.rejected, (state, action) => {
                state.loading = false;
                state.error =
                    action.payload || action.error.message;
            });
    }
});

export default studentSlice.reducer;

Understanding the Initial State

{
    data: [],
    loading: false,
    error: null
}
data Stores the fetched student records.
loading Indicates whether the request is in progress.
error Stores an error message when the request fails.

6. Configure the Redux Store

Register the student reducer in the Redux store so that React components can access the asynchronous request state.

File: store.js

import { configureStore } from "@reduxjs/toolkit";
import studentReducer from "./studentSlice";

export const store = configureStore({
    reducer: {
        students: studentReducer
    }
});

Store Structure

{
    students: {
        data: [],
        loading: false,
        error: null
    }
}

Because the reducer is registered under the students key, the component can select the data using state.students.data.

7. Fetch and Display Data in React

Use useDispatch() to start the asynchronous request and useSelector() to read the data, loading state, and error message.

File: StudentList.jsx

import { useEffect } from "react";

import {
    useDispatch,
    useSelector
} from "react-redux";

import { fetchStudents } from "./studentSlice";

function StudentList() {
    const dispatch = useDispatch();

    const {
        data,
        loading,
        error
    } = useSelector((state) => state.students);

    useEffect(() => {
        dispatch(fetchStudents());
    }, [dispatch]);

    if (loading) {
        return <p>Loading students...</p>;
    }

    if (error) {
        return <p>Error: {error}</p>;
    }

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

            {data.length === 0 ? (
                <p>No students found.</p>
            ) : (
                <ul>
                    {data.map((student) => (
                        <li key={student.id}>
                            {student.name} - {student.email}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}

export default StudentList;
The useEffect() hook dispatches the request when the component mounts. React-Redux provides the selected state, and the component displays the loading message, error, or fetched records as needed.

8. Connect the Store to React

Wrap your React application with Provider so StudentList can access the Redux store.

File: main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";

import { store } from "./store";
import StudentList from "./StudentList";

createRoot(document.getElementById("root")).render(
    <StrictMode>
        <Provider store={store}>
            <StudentList />
        </Provider>
    </StrictMode>
);

9. Understand the Request Lifecycle

Async Redux Lifecycle

dispatch(fetchStudents())
↓
Pending: loading = true
↓
API Request Completes
↓

Fulfilled

Save response data

Set loading to false

Rejected

Save error message

Set loading to false

↓
React UI Displays the Result

Expected UI States

Loading

Loading students...

Success

Student names and email addresses are displayed.

Error

An error message is displayed if the request fails.

10. Handling API Errors Properly

An HTTP error response does not automatically cause fetch() to throw an exception. Check response.ok and throw or return a rejection when the status is unsuccessful.

const response = await fetch("/api/students");

if (!response.ok) {
    throw new Error(
        `Request failed: ${response.status}`
    );
}

const data = await response.json();

For a rejected thunk, custom errors returned through rejectWithValue() are available in action.payload. Other errors may be available through action.error.message.

For production applications, consider handling network errors, invalid response data, authentication failures, and retry requirements according to the API's behavior.

11. Best Practices

Keep API Logic Organized

Place asynchronous request logic in an appropriate thunk or service layer rather than mixing it into UI rendering.

Handle Every Lifecycle State

Handle pending, fulfilled, and rejected actions so users understand what is happening.

Avoid Unnecessary Requests

Consider whether data is already available before dispatching a new request, especially when components mount repeatedly.

Keep Reducers Predictable

Reducers should update state only. Perform API calls inside thunks or another suitable asynchronous layer.

12. Practice Tasks

Task 1: Fetch Students

Create a fetchStudents thunk that retrieves student records from an API.

Task 2: Handle Loading State

Show a loading message while the request is in progress.

Task 3: Handle Errors

Display a meaningful message when the request fails.

Task 4: Build a Course List

Create a separate async thunk and slice for fetching courses.

Summary

Redux Toolkit supports asynchronous operations through utilities such as createAsyncThunk(). It generates pending, fulfilled, and rejected lifecycle actions that can be handled in a slice using extraReducers. The Redux state can store the returned data, loading status, and error message. React components use useDispatch() to start requests and useSelector() to read the resulting state. This approach helps build predictable API workflows with clear loading, success, and error behavior.