React APIs & Data Fetching
React is purely a view library. To display real, dynamic data, it must communicate with an external server through an Application Programming Interface (API).
1. The Role of useEffect
We cannot fetch data directly in the main body of a component. Doing so triggers a fetch on every render, and updating state after fetching triggers a re-render... resulting in an infinite loop. We solve this by placing side effects inside the useEffect hook.
2. The Dependency Array
The second argument of useEffect is an array of dependencies. If you leave it out, the effect runs after every render. If you pass an empty array [], it runs exactly once when the component first mounts.
3. Handling States
A robust data-fetching component requires at least three pieces of state:
1. data (to store the payload)
2. loading (boolean, true until fetch completes)
3. error (to store message if something fails)