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.
await in React?
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>
);
}
data to store the response.useEffect, we create an async function called getData().await to wait for the fetch and response to complete.setData().Note: Always use try/catch blocks with await to handle potential errors gracefully.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!