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

Loading and Error States in React

In this lesson, you will learn how to manage loading, success, empty, and error states while fetching API data. You will use React's useState and useEffect Hooks to provide clear feedback to users during asynchronous operations.

1. What Are Loading and Error States?

When a React application requests data from an API, the request does not always finish immediately. It may take time to receive the response, return an empty result, or fail because of a network problem or an unsuccessful HTTP status.

Loading and error states help the application communicate what is happening instead of showing a blank page or leaving the user wondering whether the application is working.

Common UI States

  • Loading: The request is in progress.
  • Success: The request succeeded and data is available.
  • Empty: The request succeeded, but there are no records to display.
  • Error: The request failed or the response could not be processed.
Remember: Loading, empty, and error are different situations. A successful request returning an empty array should not automatically be treated as a failed request.

2. Understanding the Request Flow

Component Starts API Request
↓
Show Loading Message
↓
Wait for API Response
↓
Success → Display Data or Empty Message
OR
Failure → Display Error Message

The component starts in a loading state. When the request completes, the application updates its state and renders the appropriate message or data.

3. Create State Variables

React's useState Hook allows a component to store values that change over time. For an API request, we commonly maintain three pieces of state: the returned data, the loading status, and an error message.

State Variables
import { useState } from "react";

function Users() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    return (
        <div>
            <h2>Users List</h2>
        </div>
    );
}

export default Users;

Explanation

  • users stores the API records.
  • loading indicates whether the request is in progress.
  • error stores an error message when the request fails.
  • setUsers, setLoading, and setError update their respective states.
Initial values should match the expected data type. An empty array is useful for a list, a boolean for loading, and an empty string when no error message is present.

4. Display a Loading Message

While the API request is running, display a message so the user knows that data is being retrieved.

Conditional Loading UI
{loading && <p>Loading users...</p>}

The && operator is used here for conditional rendering. The paragraph appears only when loading is true.

Example Output

Loading users...

When the request finishes and the loading state becomes false, this loading message is no longer displayed.

5. Handle API Errors

API requests can fail because of network issues, server problems, or unsuccessful HTTP responses. Use a try/catch block to handle rejected requests and explicitly throw an error when the HTTP response is unsuccessful.

Error Handling Example
async function fetchUsers() {
    try {
        const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
        );

        if (!response.ok) {
            throw new Error("Unable to load users");
        }

        const data = await response.json();

        setUsers(data);
    } catch (err) {
        setError(err.message || "Something went wrong");
    } finally {
        setLoading(false);
    }
}

Understanding the Code

  • try contains the code that may fail.
  • response.ok checks whether the HTTP status is successful.
  • throw new Error() creates an error for an unsuccessful HTTP response.
  • catch stores the error message in state.
  • finally runs whether the try block succeeds or fails.
  • setLoading(false) ends the loading state.
Fetch does not automatically reject its Promise for HTTP error statuses such as 404 or 500. Checking response.ok is important when those responses should be treated as errors.

6. Display the Error Message

After storing an error message, display it in the interface so the user can understand that the request did not succeed.

Conditional Error UI
{error && <p role="alert">Error: {error}</p>}

Example Output

Error: Unable to load users

The role="alert" attribute helps assistive technologies identify important feedback. Keep error messages understandable and avoid exposing sensitive technical details.

7. Complete React Example

The following component combines loading, success, empty, and error states in one example. It fetches user data, checks the response, and renders the appropriate interface.

Users.jsx
import { useEffect, useState } from "react";

function Users() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        const controller = new AbortController();

        async function fetchUsers() {
            try {
                setLoading(true);
                setError("");

                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users",
                    { signal: controller.signal }
                );

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

                const data = await response.json();

                setUsers(data);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err.message || "Something went wrong");
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        fetchUsers();

        return () => {
            controller.abort();
        };
    }, []);

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

    if (error) {
        return <p role="alert">Error: {error}</p>;
    }

    if (users.length === 0) {
        return <p>No users available.</p>;
    }

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

            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        <strong>{user.name}</strong>
                        {" - "}
                        {user.email}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default Users;

Step-by-Step Explanation

  1. useState stores the records, loading status, and error message.
  2. useEffect starts the API request when the component mounts.
  3. AbortController allows the request to be cancelled during cleanup.
  4. The request begins with loading enabled and the previous error cleared.
  5. The response is checked before its JSON body is parsed.
  6. Successful data is stored using setUsers(data).
  7. Errors are stored in state, except for an intentional request cancellation.
  8. The finally block ends loading unless the request was aborted.
  9. Conditional returns render loading, error, empty, or success UI.
Cancelling a request in Effect cleanup is useful when a component unmounts. In development Strict Mode, Effects may be set up and cleaned up an extra time, so request logic should handle cancellation correctly.

8. Expected UI States

Loading State

Loading users...

The application is waiting for the API response.

Success State

Samadhan - samadhan@example.com

Samiksha - samiksha@example.com

The application received records and displayed them.

Empty State

No users available.

The request succeeded, but the returned array contains no records.

Error State

Error: Failed to load users

The request failed or the response could not be processed.

9. Common Mistakes

  • Never ending loading: Set loading to false after both success and failure, typically with finally.
  • Ignoring HTTP errors: Check response.ok because Fetch does not reject automatically for 404 or 500 responses.
  • Showing an error for empty data: An empty array can be a valid successful result.
  • Updating state after cancellation: Use AbortController where appropriate and ignore abort errors.
  • Displaying unclear error messages: Tell users what happened without revealing sensitive server details.
  • Showing multiple states simultaneously: Use an intentional order for loading, error, empty, and success rendering.

10. Practice Tasks

Task 1: Add a Loading Message

Fetch users from https://jsonplaceholder.typicode.com/users and display "Loading users..." while the request is in progress.

Task 2: Handle Failed Responses

Check response.ok and display an error message when the server returns an unsuccessful HTTP status.

Task 3: Display an Empty State

Display "No records available" when the API returns an empty array after a successful request.

Task 4: Add Request Cleanup

Use AbortController to cancel the Fetch request when the component's Effect is cleaned up.

Task 5: Create a Posts Component

Fetch posts from https://jsonplaceholder.typicode.com/posts and implement loading, error, empty, and success states.

Summary

In this lesson, you learned how to manage loading, success, empty, and error states while working with APIs in React. You used useState to store data and status messages, useEffect to start the request, async and await to handle asynchronous operations, try/catch/finally for error handling, and AbortController for request cancellation. In the next lesson, you will learn how to send POST requests from React to submit data to an API.