In this article, we will see how async/await works in react rendering

Both of these API’s are co-related and are used to write asynchronous code in javascript. These are based on the promise API. The async keyword is used to declare the asynchronous function while an await is used to wait for the promise to resolve.

When we use async/await in reactjs

We may need to perform asynchronous operations when rendering a component in React. For example, a component may need to fetch data from the server or perform some other long-running operation. In these cases, async/await can be used.

Let us see an example program with async/await and has a component to fetch data from a server when it is rendered.

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('/api/data');
      const data = await response.json();
      setData(data);
    }

    fetchData();
  }, []);

  return (
    <div>
      {data ? (
        <div><p>Rendering the data </p></div>
      ) : (
        <div>Loading...</div>
      )}
    </div>
  );
}

Explanation

In the above example, we define an asynchronous function ‘fetchData’ using the async keyword. We used await inside the function to wait for the response from the server and for the data to be parse as a JSON. We then update the state of the component with the retrieved data.

The fetchData function is called inside the useEffect hook. By passing the empty array as the second argument to useEffect, we ensure it runs only once when the component is mounted.

Categorized in:

Tagged in: