React is designed to build dynamic user interfaces, and often, it needs to interact with servers to fetch or submit data. These operations are asynchronous, meaning they happen in the background and donβt block the UI.
In simple terms, asynchronous means βnot happening at the same time.β In JavaScript (and React), it allows the browser to continue rendering UI while waiting for something to finish β like fetching data from an API.
async/await in useEffect()
import React, { useState, useEffect } from 'react';
function Quote() {
const [quote, setQuote] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchQuote() {
try {
const response = await fetch('https://api.quotable.io/random');
const data = await response.json();
setQuote(data.content);
} catch (err) {
setQuote('Failed to load quote.');
} finally {
setLoading(false);
}
}
fetchQuote();
}, []);
return (
<div>
{loading ? <p>Loading...</p> : <p>{quote}</p>}
</div>
);
}
useEffect runs when the component mounts.fetchQuote function makes an async call to an API.await pauses until the data is returned.setQuote updates the state with the result.try/catch.finally to stop loading even if fetch fails.useEffect; create an inner async function.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!