32. API Calls in React
Connecting to the Real World
Your React components will rarely rely on hardcoded data. They need to fetch user profiles, product lists, or news articles from a backend server. Fetching data is a Side Effect, which means it must be strictly managed inside the useEffect hook to prevent infinite re-rendering loops.
The Standard Fetch Pattern
Because network requests take time, you must manage three distinct states in your UI: Loading, Success, and Error. If you don't track loading state, the user will stare at a blank screen.
Why Define the Async Function Inside?
You cannot make the useEffect callback itself async (e.g., useEffect(async () => {...})). React requires effects to return either nothing or a cleanup function. Async functions return Promises, which breaks React. The standard pattern is to define the async function inside the effect, and then immediately call it.
Knowledge Check
Ready to test your understanding of 32. API Calls in React?