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

Fetching Data Using Fetch API

In this lesson, you will learn how to request data from an API using JavaScript's Fetch API, understand HTTP responses, process JSON data, and handle basic request errors in a React application.

1. What Is the Fetch API?

The Fetch API is a built-in JavaScript feature used to make HTTP requests to servers and other web resources. It allows a React application to retrieve information from an API without installing an additional HTTP library.

For example, a student management application may request a list of students from a backend API and then display the returned information on the page.

Why Use Fetch API?

  • It is built into modern browsers.
  • It supports HTTP methods such as GET and POST.
  • It returns a Promise that can be handled using .then() or async/await.
  • It can read JSON responses from an API.
  • It can be used with React state and effects to display remote data.
Remember: Fetch is a JavaScript browser API. React does not provide a separate function named fetch().

2. How Fetch API Works

React Application
↓
fetch(API URL)
↓
Server Returns HTTP Response
↓
Read Response as JSON
↓
Use Data in React UI

Fetch sends a request to the specified URL. The server returns an HTTP response. The application then checks the response, reads the body in the required format, and uses the resulting data.

  1. Specify the API endpoint.
  2. Call fetch() to send the request.
  3. Check whether the HTTP response indicates success.
  4. Read the response body using response.json().
  5. Use the parsed data in the application.

3. Making a Basic GET Request

A GET request is commonly used to retrieve information from an API. The following example uses JSONPlaceholder, a public test API.

Basic Fetch Example
fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => {
        if (!response.ok) {
            throw new Error("Failed to fetch users");
        }

        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error("Error:", error);
    });

Explanation

  • fetch(url) sends a GET request by default.
  • response contains the HTTP status and response information.
  • response.ok is true for HTTP status codes from 200 through 299.
  • throw new Error() moves execution to the error handler when the response is unsuccessful.
  • response.json() reads and parses the response body as JSON.
  • console.log(data) displays the parsed result in the browser console.
  • catch() handles rejected requests and errors thrown in the preceding Promise chain.
Fetch does not automatically reject its Promise for HTTP errors such as 404 or 500. Always check response.ok when unsuccessful HTTP responses need to be handled as errors.

4. Understanding the API Response

The example endpoint returns an array of user objects. Each object contains properties such as an ID, name, username, email, and address.

Sample JSON Response
[
    {
        "id": 1,
        "name": "Leena",
        "username": "leena123",
        "email": "leena@example.com"
    },
    {
        "id": 2,
        "name": "Samiksha",
        "username": "samiksha123",
        "email": "samiksha@example.com"
    }
]

This is an illustrative sample of the response structure. The actual values returned by the endpoint may be different.

After parsing the response, JavaScript can access properties using expressions such as data[0].name or data[0].email.

Example Values

First user's name: data[0].name

First user's email: data[0].email

Second user's name: data[1].name

5. Using Fetch API in a React Component

In React, API data is usually stored in state so that the component can display it. The useState Hook stores the users, and useEffect starts the request when the component is mounted.

This example introduces the basic integration of Fetch with React. Loading and error UI will be covered in more detail in a later lesson.

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

function Users() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
            .then(response => {
                if (!response.ok) {
                    throw new Error("Failed to fetch users");
                }

                return response.json();
            })
            .then(data => {
                setUsers(data);
            })
            .catch(error => {
                console.error("Error fetching users:", error);
            });
    }, []);

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

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

export default Users;

Step-by-Step Explanation

  1. useState([]) creates a state variable named users with an empty array as its initial value.
  2. useEffect() runs the effect after the component has been rendered.
  3. The empty dependency array [] means the effect is scheduled to run after the initial mount.
  4. Fetch requests the user data from the API.
  5. setUsers(data) stores the parsed response in React state.
  6. users.map() creates a list item for each user.
  7. key={user.id} provides React with a stable key for each list item.
If the request fails in this example, the error is logged in the console and the list remains empty. The component does not yet display a user-friendly error message.

6. Why Use useEffect for API Requests?

Fetching data is a side effect because it involves communication with an external system. The useEffect Hook is commonly used to start a request when a component is mounted or when selected dependencies change.

useEffect Syntax
useEffect(() => {
    // Start an API request here
}, []);
  • Empty dependency array: The effect is scheduled after the initial mount.
  • Dependencies included: The effect can run again when a dependency changes.
  • No dependency array: The effect runs after every render, which may cause repeated requests if used carelessly.
In React Strict Mode during development, React may run an additional setup and cleanup cycle for Effects. This can make a request appear more than once during development. Effects should be written to handle cleanup and repeated execution appropriately.

7. Fetch API vs React State

Fetch and state have different responsibilities. Fetch retrieves information from the server, while React state stores the data that the component uses to render its interface.

  • Fetch API: Sends the HTTP request.
  • response.json(): Parses the response body.
  • useState: Stores the data in the component.
  • setUsers(data): Updates the stored data.
  • users.map(): Renders the user records.

8. Common Mistakes

  • Forgetting response.json(): The response body must be parsed before using JSON data.
  • Ignoring HTTP errors: Check response.ok because a 404 or 500 response does not automatically reject the Fetch Promise.
  • Not handling rejected requests: Use error handling for network failures and parsing errors.
  • Updating state incorrectly: Use the state setter such as setUsers(data).
  • Missing list keys: Give mapped elements stable keys such as user.id.
  • Putting fetch directly in the render body: This may trigger repeated requests on every render. Use an appropriate Effect or event handler instead.

9. Practice Tasks

Task 1: Fetch User Data

Write a Fetch request to retrieve data from https://jsonplaceholder.typicode.com/users and display the result in the browser console.

Task 2: Display User Names

Create a React component that fetches users and displays only their names using map().

Task 3: Display Emails

Modify the component to display each user's name and email address in a list.

Task 4: Check the Response

Add a check for response.ok and throw an error when the HTTP response is unsuccessful.

Task 5: Fetch Posts

Use https://jsonplaceholder.typicode.com/posts to retrieve posts and display their titles in a React component.

Summary

In this lesson, you learned how to make GET requests using the Fetch API, inspect HTTP responses, check response.ok, parse JSON data, and handle errors with Promise methods. You also learned how to combine Fetch with useEffect and useState to retrieve and display user records in a React component. In the next lesson, you will explore asynchronous JavaScript using async and await to make API request code easier to read.