Fetching data in React
You'll learn to load data from an API when a component appears, and show loading, error and data states.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want a screen that shows a list of users from a server. The data is not there when the component first renders. It arrives later, maybe after a second, maybe never.
So you combine three things you know: state to hold the data, an effect to start the request after the first render, and conditional rendering to show the right thing at each moment.
const [users, setUsers] = useState([]);useEffect(() => {fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json()).then((data) => setUsers(data));}, []);
The order is: first render with the empty array, the effect starts the request, the data arrives,
setUsers saves it, and React renders again with the list. The first screen always shows the starting
state, so give the person something useful: a loading state that shows "Loading...", and an error
state for when the request fails.
The [] matters. It means "fetch once, when the screen appears".
People often call fetch straight in the component body, outside an effect. Then every render
starts a request. When the data arrives, setUsers renders again, which fetches again, forever.
When you read a fetching component, find three things: where the request starts (the effect), where the answer is saved (the setter), and what the screen shows while waiting (the loading check).
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function Users() {2 const [users, setUsers] = useState([]);34 useEffect(() => {5 fetch("https://jsonplaceholder.typicode.com/users")6 .then((res) => res.json())7 .then((data) => setUsers(data));8 }, []);910 return <p>{users.length} users</p>;11}1213// This API sends back 10 users.
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3Why is
fetchput insideuseEffectand not straight in the component body? - 2 / 3With
useState([])and a fetch in an effect, what does the first screen show? - 3 / 3Why keep a
loadingstate?
Explain it back
How confident are you with Fetching data in React?
Done
useEffect and say what the screen shows before, during and after loading.