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

API Error Handling in React

CIIT Training Institute | React API Integration

1. Introduction to API Error Handling

When React applications communicate with APIs, different errors can occur. The server may return an error response, the internet connection may fail, or the response may contain invalid data.

API error handling helps us detect these problems and display meaningful messages instead of leaving users confused.

Important: The Fetch API does not automatically throw an error for HTTP error responses such as 404 or 500. We must check the response using response.ok.

2. Types of API Errors

Error Type Description Example
Network Error The request cannot reach the server. Internet connection lost.
404 Not Found The requested resource does not exist. Invalid API endpoint.
401 Unauthorized Authentication is missing or invalid. Invalid access token.
500 Server Error The server encountered a problem. Internal server failure.
Invalid JSON The response cannot be parsed as JSON. Malformed response data.

3. Using response.ok

The response.ok property is true when the HTTP status code indicates success, usually in the 200–299 range. If it is false, we can throw an error and handle it in the catch block.

Checking an HTTP Response
const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
);

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

const data = await response.json();
console.log(data);
Remember: A failed HTTP status does not automatically reject the Fetch promise. Check response.ok explicitly.

4. Using try, catch and finally

JavaScript provides three useful blocks for handling errors during API requests.

  • try: Contains the code that may fail.
  • catch: Handles errors thrown by the request or processing logic.
  • finally: Runs whether the request succeeds or fails.
Basic Error Handling
try {
    const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
    );

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

    const data = await response.json();
    console.log(data);
} catch (error) {
    console.error("API Error:", error.message);
} finally {
    console.log("Request completed.");
}

5. Complete React Example

In this example, we fetch users from an API and display the data. If the request fails, React displays an error message. The loading indicator is cleared after the request finishes.

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

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

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

                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users"
                );

                if (!response.ok) {
                    throw new Error(
                        `Unable to load users. Status: ${response.status}`
                    );
                }

                const data = await response.json();

                if (!Array.isArray(data)) {
                    throw new Error(
                        "Invalid data received from the server."
                    );
                }

                setUsers(data);
            } catch (err) {
                setError(
                    err instanceof Error
                        ? err.message
                        : "Something went wrong."
                );
            } finally {
                setLoading(false);
            }
        }

        fetchUsers();
    }, []);

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

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

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

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

export default APIErrorHandling;

6. How Error Handling Works

Start API Request
↓
Check HTTP Response
↓
Is response.ok true?
↓
Yes
Parse JSON and Display Data
No / Request Failed
Catch Error and Display Message
↓
Finally: Stop Loading

7. Best Practices

  • Always check response.ok for Fetch requests.
  • Display clear, user-friendly error messages.
  • Use finally to reset loading state.
  • Validate API data before using it.
  • Do not expose passwords, access tokens or sensitive server details in error messages.
  • Log technical details appropriately during development.
  • For retry functionality, use a deliberate retry strategy rather than retrying every error indefinitely.

8. Practice Tasks

  1. Fetch posts from JSONPlaceholder and display them.
  2. Use an invalid endpoint and display a suitable error message.
  3. Display a loading message while fetching data.
  4. Handle HTTP error responses using response.ok.
  5. Validate the response data before rendering it.
  6. Add a Retry button that allows users to try the request again.

Summary

API error handling makes React applications more reliable and user-friendly. By checking HTTP responses, using try-catch-finally, validating returned data and displaying meaningful messages, we can manage common network and server problems effectively.