Fetching Data the React Way
Load remote data into React components using useEffect and useState, render loading and error states declaratively, and keep the UI in sync with your data.
We'll cover the following...
With traditional JavaScript, we fetch data and imperatively stitch DOM nodes together. In React, we fetch once and render declaratively. The component state becomes the single source of truth, so our UI re-renders automatically when the data arrives or fails. The key is to place side effects — like data fetching — inside useEffect, manage loading/error in state, and render the appropriate UI for each state.
Core idea
A React component should be a pure mapping from state to UI. Data fetching is a side effect that happens after the component is on screen. We’ll:
Initialize
loading,error, anddatastate.Trigger the fetch in
useEffect(so it runs after ...