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

Using Async and Await in React

In this lesson, you will learn how JavaScript async and await simplify asynchronous operations, how to fetch API data using async functions, and how to handle errors with try and catch in React applications.

1. What Is Asynchronous JavaScript?

JavaScript executes code in an order, but some operations take time to complete. Examples include requesting information from a server, reading a file, or waiting for a network response.

These operations are asynchronous when JavaScript can continue doing other work instead of waiting synchronously for the operation to finish.

When React requests data from an API, the response may take some time. Async JavaScript allows the application to manage that operation without blocking the browser's main thread while waiting for the network response.

Remember: Asynchronous code helps manage operations that complete later. It does not mean that every line of code runs simultaneously.

2. What Is a Promise?

A Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation.

A Promise has three possible states:

  • Pending: The operation has not completed yet.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

The Fetch API returns a Promise. We can process its result with .then() and handle rejected operations with .catch().

Promise Example
fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

This is a Promise-based approach. Async and await provide another way to write asynchronous code that often looks more like step-by-step synchronous code.

3. What Is Async?

The async keyword is used before a JavaScript function declaration or function expression to make that function return a Promise.

Async Function
async function greet() {
    return "Hello, React!";
}

greet().then(message => {
    console.log(message);
});

Explanation

  • async declares an asynchronous function.
  • The function returns a Promise.
  • A returned string becomes the fulfilled value of that Promise.
  • .then() reads the fulfilled value.

Expected Console Output

Hello, React!

Even if an async function returns an ordinary value, callers receive a Promise that fulfills with that value.

4. What Is Await?

The await keyword can be used inside an async function to wait for a Promise to settle. If the Promise is fulfilled, the await expression evaluates to its result. If the Promise is rejected, the await expression throws the rejection reason.

Async and Await Example
function getMessage() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("Data received successfully");
        }, 1000);
    });
}

async function displayMessage() {
    const message = await getMessage();

    console.log(message);
}

displayMessage();

Explanation

  1. getMessage() returns a Promise.
  2. The Promise resolves after one second.
  3. await getMessage() waits for that Promise's result.
  4. The returned message is assigned to the message variable.
  5. The message is displayed in the console.

Expected Console Output

Data received successfully

Await pauses the execution of the surrounding async function until the Promise settles. It does not block the entire JavaScript thread while waiting for the Promise.

5. Fetch API Using Async and Await

We can combine Fetch with async and await to request data from an API. This makes it easier to read the request, check the response, and process the JSON data in sequence.

Fetch with Async/Await
async function fetchUsers() {
    const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
    );

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

    const users = await response.json();

    console.log(users);
}

fetchUsers().catch(error => {
    console.error("Error:", error);
});

Step-by-Step Explanation

  1. async function fetchUsers() defines an async function.
  2. await fetch(...) waits for the HTTP response.
  3. response.ok checks whether the status is successful.
  4. If the response is unsuccessful, an error is thrown.
  5. await response.json() reads and parses the JSON response body.
  6. console.log(users) displays the returned data.
  7. .catch() handles errors from the async function's returned Promise.
Important: Fetch does not reject automatically for HTTP status codes such as 404 or 500. Checking response.ok lets you handle unsuccessful HTTP responses.

6. Handling Errors with Try and Catch

When using async and await, we can handle errors with a try...catch block. The try block contains the code that may fail, while the catch block handles a thrown error or rejected Promise.

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

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

        const users = await response.json();

        console.log(users);
    } catch (error) {
        console.error("Request failed:", error.message);
    }
}

fetchUsers();

Why Is Try/Catch Useful?

  • It handles network failures.
  • It handles errors explicitly thrown for unsuccessful HTTP responses.
  • It can catch JSON parsing errors.
  • It keeps error handling close to the asynchronous operation.
The catch block handles the error in this example, so it is not necessary to add another catch to the same call just to handle that already-caught error.

7. Using Async/Await in a React Component

In React, we can use async and await inside a function called by useEffect. The Effect callback itself should not be declared async because React expects it to return either nothing or a cleanup function.

The common approach is to declare an inner async function and call it from the Effect.

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

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

    useEffect(() => {
        async function loadUsers() {
            try {
                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users"
                );

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

                const data = await response.json();

                setUsers(data);
            } catch (error) {
                console.error("Error loading users:", error);
            }
        }

        loadUsers();
    }, []);

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

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

export default Users;

How This Component Works

  1. useState([]) initializes an empty users array.
  2. useEffect() starts the data-loading operation after the component mounts.
  3. loadUsers() is an async function defined inside the Effect.
  4. The Fetch request waits for the response using await.
  5. The JSON body is parsed using another await.
  6. setUsers(data) updates React state with the received users.
  7. React renders the list using users.map().
This introductory component logs errors in the console. A production-ready component should also show loading and error messages to users. We will study those states in a separate lesson.

8. Promise Then/Catch vs Async/Await

Both approaches can perform the same asynchronous operation. Async and await often make sequential operations easier to read, while Promise chaining remains a useful and valid approach.

Using Then and Catch

Promise-Based Approach
fetch("/api/users")
    .then(response => {
        if (!response.ok) {
            throw new Error("Request failed");
        }

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

Using Async and Await

Async/Await Approach
async function getUsers() {
    try {
        const response = await fetch("/api/users");

        if (!response.ok) {
            throw new Error("Request failed");
        }

        const data = await response.json();

        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

getUsers();
Both examples assume that /api/users is a valid endpoint on the current origin. Choose the style that makes your asynchronous logic easiest to understand and maintain.

9. Common Mistakes

  • Using await outside a valid context: In ordinary JavaScript functions, await must be inside an async function. Top-level await is available in supported module contexts.
  • Forgetting response.json(): The response object is not the parsed JSON data itself.
  • Ignoring HTTP status: Check response.ok when HTTP error responses should throw an error.
  • Missing error handling: Use try/catch or handle the Promise rejection.
  • Making the Effect callback async: Define an inner async function and call it from useEffect instead.
  • Updating state after a component is no longer relevant: For more advanced components, consider cleanup and request cancellation using AbortController.

10. Practice Tasks

Task 1: Create an Async Function

Create an async function that returns a welcome message and display the result using await.

Task 2: Fetch Users

Write an async function that retrieves data from https://jsonplaceholder.typicode.com/users and logs the parsed result.

Task 3: Add Error Handling

Add a try/catch block and check response.ok before parsing the response.

Task 4: Display Posts in React

Create a React component that retrieves posts from https://jsonplaceholder.typicode.com/posts using async and await, then displays the post titles.

Task 5: Compare Both Approaches

Write one API request using .then() and .catch(), then rewrite it using async, await, and try/catch.

Summary

In this lesson, you learned about asynchronous JavaScript, Promises, async functions, the await keyword, and error handling with try/catch. You also learned how to retrieve API data with Fetch inside a React useEffect, update state with useState, and display the returned information. In the next lesson, you will learn how to display API data in a React interface in a structured and user-friendly way.