REACT Tutorial



AWAIT IN REACT


Await in React

In React, asynchronous operations are commonly performed when working with APIs, dynamic data, or any side effects. The await keyword allows us to pause JavaScript execution until a Promise is resolved β€” making asynchronous code easier to read and write.

Why use await in React?
  • To wait for data to load before updating the state.
  • To write cleaner, readable async code compared to .then() chaining.
  • To avoid race conditions or unexpected renders.

Using await inside useEffect()

The await keyword should be used inside an async function. Since React’s useEffect cannot be directly marked as async, we create an inner async function and call it inside useEffect.

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

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

  useEffect(() => {
    const getData = async () => {
      const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
      const json = await res.json();
      setData(json);
    };
    getData();
  }, []);

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

Code Breakdown:

  • Step 1: We define a state variable data to store the response.
  • Step 2: Inside useEffect, we create an async function called getData().
  • Step 3: We use await to wait for the fetch and response to complete.
  • Step 4: Finally, we store the data using setData().

Note: Always use try/catch blocks with await to handle potential errors gracefully.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review