⏳ Promises & Async/Await in React
JavaScript handles asynchronous operations using Promises and async/await. These are essential for working with APIs, timers, and other non-blocking tasks — especially in React apps.
📦 1. What is a Promise?
A Promise is an object that represents a future value. It can be in one of three states: pending
, fulfilled
, or rejected
.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded!");
}, 1000);
});
promise.then(data => console.log(data));
🧠 2. Using Async/Await
async/await
is syntactic sugar over Promises, making asynchronous code look and behave like synchronous code.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();
⚠️ 3. Error Handling with try/catch
async function fetchUser() {
try {
const res = await fetch("/user");
const user = await res.json();
console.log(user);
} catch (error) {
console.error("Error fetching user:", error);
}
}
⚛️ 4. Using with React useEffect()
Async calls should be handled inside useEffect
for side effects like API calls:
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function getUsers() {
const res = await fetch("https://api.example.com/users");
const data = await res.json();
setUsers(data);
}
getUsers();
}, []);
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
✅ 5. Summary
- Promises allow handling async operations via
.then()
and.catch()
- async/await simplifies syntax and supports
try/catch
error handling - Always use async calls in
useEffect
in React