How to manage multiple API calls in React?

There are several ways to manage multiple API calls in React, depending on your specific use case and requirements. Here are a few common approaches:

  1. Using useEffect and useState: You can use the useEffect hook to fetch data from multiple APIs and useState to store the fetched data. You can make multiple API calls in the useEffect hook by using Promise.all or async/await. Here is an example:
import React, { useState, useEffect } from 'react'; const MyComponent = () => { const [data1, setData1] = useState(null); const [data2, setData2] = useState(null); useEffect(() => { const fetchData = async () => { const [response1, response2] = await Promise.all([ fetch('API_ENDPOINT_1'), fetch('API_ENDPOINT_2'), ]); const data1 = await response1.json(); const data2 = await response2.json(); setData1(data1); setData2(data2); }; fetchData(); }, []); return ( <div> {/* render data1 and data2 */} </div> ); }; export default MyComponent;
  1. Using async/await and fetch: You can also make multiple API calls using async/await and fetch directly in your component. This approach is simpler but may result in nested callbacks. Here is an example:
import React, { useState } from 'react'; const MyComponent = () => { const [data1, setData1] = useState(null); const [data2, setData2] = useState(null); const fetchData = async () => { const response1 = await fetch('API_ENDPOINT_1'); const response2 = await fetch('API_ENDPOINT_2'); const data1 = await response1.json(); const data2 = await response2.json(); setData1(data1); setData2(data2); }; useEffect(() => { fetchData(); }, []); return ( <div> {/* render data1 and data2 */} </div> ); }; export default MyComponent;
  1. Using third-party libraries: If your API calls are complex and require additional features like caching, retries, and request deduplication, you can use third-party libraries like Axios or SWR. These libraries provide more advanced features for managing API calls in React.

Overall, the best approach for managing multiple API calls in React depends on the complexity of your application and your specific requirements. Consider the trade-offs between simplicity, performance, and flexibility when choosing an approach.