Junior — Middle
How can asynchronous calls be organized in React using hooks?
sobes.tech AI
Answer from AI
In React, asynchronous calls are usually organized using the useEffect hook. Inside useEffect, you can call asynchronous functions, for example, to load data from a server. Since the effect itself cannot be asynchronous, an asynchronous function is created and invoked inside it.
Example:
import React, { useState, useEffect } from 'react';
function DataLoader() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error loading data:', error);
} finally {
setLoading(false);
}
}
fetchData();
}, []); // empty dependency array — called once on mount
if (loading) return <div>Loading...</div>;
return <div>Data: {JSON.stringify(data)}</div>;
}
This approach allows performing asynchronous operations when the component mounts and updating the state as data is received.