How to handle asynchronous operations in React

Key takeaways:

  • React supports using promises combined with the async/await syntax to handle asynchronous operations seamlessly.

  • The fetch API allows data fetching in React components, enabling updates to the state with asynchronous responses.

  • Axios offers a streamlined way to handle HTTP requests with built-in support for promises and JSON parsing.

  • React Query simplifies asynchronous tasks by integrating data fetching, caching, and server state synchronization.

  • Conditional rendering in React helps manage loading spinners and error messages for a smoother user experience.

Asynchronous operations are an essential part of web development. They enable tasks like fetching data from APIs, updating the UI, and handling user interactions without blocking the main thread. React provides several approaches to handling asynchronous operations. In this Answer, we will explore some commonly used techniques for handling asynchronous operations in React.

Using promises in React

Promises are a powerful tool for handling asynchronous operations. They represent an asynchronous task’s eventual completion (or failure) and allow us to combine multiple operations. React supports using promises in combination with the async/await syntax for handling asynchronous operations.

Method 1: Fetching data using the fetch API

Here’s an example of fetching data using the fetch API and updating the state in a React component:

Explanation

In the App.js file above:

  • Lines 6–8: We set up an effect using the useEffect hook. It runs the fetchData function when the component mounts ([] dependency array indicates that the effect only runs once). This is crucial for React data fetching.

  • Lines 10–12: We define the fetchData function that uses the Fetch API to send a GET request to the specified URL and waits for the response using the await keyword. The fetch function returns a promise that resolves the response.

  • Lines 13–14: This extracts the JSON data from the response by calling the json() method on the response object and waits for the result and then updates the data state variable with the fetched result.

  • Lines 15–17: This catches any errors that occur during the asynchronous operations in React and logs the error to the console.

Method 2: Using Axios for HTTP requests in React

Axios is a popular HTTP client library that simplifies making HTTP requests in JavaScript. It supports promises and provides features like request cancellation and automatic JSON parsing, making it a great choice for React API calls.

Example

Here’s an example of using Axios to fetch data in a React component:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your App</title>
</head>
<body>
  <div id="root"></div>
  <div id="dialog-root"></div>
</body>
</html>
Data fetching with Axios

Explanation

In the App.js file above:

  • Line 5: We use the useState hook to declare a state variableState variable is used to store and manage data that can change over time within a component. data and a corresponding setter function setData. The initial value of data is an empty array.

  • Lines 7–9: This sets up an effect using the useEffect hook. It runs the fetchData function when the component mounts ([] dependency array indicates that the effect

  • Lines 11–13: We define an asynchronous function named fetchData using the async keyword that uses the Axios library to send a GET request to the specified URL and waits for the response using the await keyword. The axios.get function returns a promise that resolves to the response.

  • Line 14: This updates the data state variable with the data from the response. Axios automatically parses the response and provides the parsed data in the data property of the response object.

  • Lines 20–23: The return statement contains the JSX that defines the component's UI. It displays a heading and conditionally renders a list of items if data has a length greater than 0. If data is empty, it displays a “Loading data...” message.

Method 3: Using React Query for data fetching

React Query is a powerful data fetching and caching library for React. It simplifies handling asynchronous operations by providing hooks that handle data fetching, caching, and synchronizing server state with the UI.

Example

Here’s an example of using React Query to fetch data:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your App</title>
</head>
<body>
  <div id="root"></div>
  <div id="dialog-root"></div>
</body>
</html>
Using React Query for fetching data

Explanation

In the App.js file above:

  • Line 4: We define an asynchronous function named fetchTodoData that will be used as the data-fetching function for the query.

  • Line 5: This uses the fetch API to send a GET request to the specified URL and waits for the response using the await keyword. The fetch function returns a promise that resolves the response.

  • Lines 6–7: This extracts the JSON data from the response by calling the json() method on the response object, waits for the result, and returns the fetched data.

  • Line 11: Here, the useQuery hook is used to fetch data using the fetchTodoData function. It provides a unique query key ('todos') and a fetching function. The hook returns an object with properties data (the fetched data), isLoading (a boolean indicating whether the data is being fetched), and isError (a boolean indicating whether an error occurred during the fetching process).

Managing loading and error states in React

When handling asynchronous operations, it's important to provide feedback to the user during loading and error states. React offers conditional renderingconditional rendering is the process of displaying different content based on certain conditions or states. to handle these scenarios.

Example

For instance, we can show a loading spinner while waiting for data or display an error message if an operation fails.

Explanation

  • Line 5: We use the useState hook to declare a state variable isLoading and a corresponding setter function setIsLoading. The initial value of isLoading is set to true, indicating that the data is still loading.

  • Line 6: This line declares a state variable error and a setter function setError. The initial value of error is set to null, indicating that no error has occurred yet.

  • Line 7: This line declares a state variable data and a setter function setData. The initial value of data is an empty array.

  • Line 16: This line simulates a delay of 2 seconds using a promise and the setTimeout function. This is used to demonstrate the loading spinner in the UI.

  • Line 24: This sets the isLoading state variable to false, indicating that the data fetching process is complete.

Knowledge test

Let’s attempt a short quiz to assess our understanding.

Q

What is the best approach for handling data fetching and caching in React applications?

A)

Using async/await with the fetch API

B)

Using Axios for all HTTP requests

C)

Using the useEffect hook to directly update state with fetched data

D)

Using React Query for data fetching, caching, and synchronization

Ready to bring your web development skills to life? With Build an E-learning Website with the MERN Stack, you’ll create a dynamic course catalog site, mastering database design, API development, and seamless frontend-backend integration.

Conclusion

Handling asynchronous operations is an important aspect of React development. By mastering techniques such as promises, async/await, Axios, and libraries like React Query, we can effectively manage asynchronous tasks and create responsive user interfaces. Understanding how to manage loading and error states ensures a smoother user experience and prevents potential pitfalls like memory leaks. By using these techniques, we can build robust and efficient React applications that gracefully handle asynchronous operations, resulting in better performance and user satisfaction.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is async in React?

In React, async refers to the handling of asynchronous operations, which are tasks that occur outside of the main thread without blocking the UI. Using async functions with the await keyword allows developers to write code that performs actions like fetching data, making API calls, or performing complex calculations without freezing the interface, ensuring a smoother user experience.


What is an example of asynchronous operations?

An example of asynchronous operations in React is fetching data from an external API. For instance, using the fetch function or Axios to request data from a server allows the application to continue running while waiting for the data to be retrieved. This means users can interact with the UI without being blocked while the data is being loaded.


Is React asynchronous or synchronous?

React is primarily synchronous in its execution of state updates and rendering processes, but it supports asynchronous operations through features like useEffect, async/await, and third-party libraries such as React Query. These tools allow React to handle tasks like data fetching and timers without blocking the UI, enabling smoother and more responsive user experiences.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved