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.
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().
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 greet() {
return "Hello, React!";
}
greet().then(message => {
console.log(message);
});
Explanation
asyncdeclares 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!
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.
function getMessage() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data received successfully");
}, 1000);
});
}
async function displayMessage() {
const message = await getMessage();
console.log(message);
}
displayMessage();
Explanation
getMessage()returns a Promise.- The Promise resolves after one second.
await getMessage()waits for that Promise's result.- The returned message is assigned to the
messagevariable. - The message is displayed in the console.
Expected Console Output
Data received successfully
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.
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
async function fetchUsers()defines an async function.await fetch(...)waits for the HTTP response.response.okchecks whether the status is successful.- If the response is unsuccessful, an error is thrown.
await response.json()reads and parses the JSON response body.console.log(users)displays the returned data..catch()handles errors from the async function's returned Promise.
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.
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.
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.
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
useState([])initializes an empty users array.useEffect()starts the data-loading operation after the component mounts.loadUsers()is an async function defined inside the Effect.- The Fetch request waits for the response using
await. - The JSON body is parsed using another
await. setUsers(data)updates React state with the received users.- React renders the list using
users.map().
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
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 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();
/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.okwhen 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.