Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Phase 5 · 9 / 9Fetching data in React
Phase 5React
9 topics · 5–6 wks
  1. 1Components and JSX
  2. 2Props
  3. 3State with useState
  4. 4Events in React
  5. 5Showing things conditionally
  6. 6Lists and keys
  7. 7Forms and inputs
  8. 8useEffect
  9. 9Fetching data in React
JourneyPhase 5Fetching data in React
01 / 09Overview

Fetching data in React

You'll learn to load data from an API when a component appears, and show loading, error and data states.

Why it mattersAlmost every app screen shows data from a server, and the same pattern works in React Native.
about 90 min·needs: useEffect, Fetching real data, Loading and error states
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Docs
Synchronizing with effects: fetching datareact.dev · official docs · 10 min · English
MMamun's noteRead the "Fetching data" part only. The ignore flag in the cleanup stops an old answer from replacing a newer one; just notice it for now.
Video
Full React tutorial #17: fetching data with useEffectYouTube · Net Ninja · 8 min · English
MMamun's noteWatch all of it. He fetches from a small local server set up in the video before, but the idea is the same with any URL. Notice the error at 4:02 when the data is still null, and how he fixes it.
VideoOptional
Full React tutorial #19: handling fetch errorsYouTube · Net Ninja · 8 min · English
MMamun's noteAdds an error state and checks res.ok, so a failed request shows a message instead of loading forever.
VideoOptional
4 ways to fetch data from an API in React (Bangla)YouTube · Learn with Sumit · 7 min · Bangla
MMamun's noteIn Bangla. Watch 0:21–7:35, the plain fetch part. The rest shows libraries (axios, react-query) you don't need yet.
03 / 09

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).

Words to recognise
fetchuseEffectloading stateerror state
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

App.jsx6 notes
1import { useEffect, useState } from "react";
2export default function Users() {
3 const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
Mentor note · line 4
Three pieces of state, one for each thing the screen can show. Loading starts as true, because nothing has arrived yet.
5 const [error, setError] = useState(null);
6 useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
8 .then((res) => res.json())
.then((data) => setUsers(data))
10 .catch(() => setError("Could not load users."))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
14 if (error) return <p>{error}</p>;
15 return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
16}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 1
1function Users() {
2 const [users, setUsers] = useState([]);
3
4 useEffect(() => {
5 fetch("https://jsonplaceholder.typicode.com/users")
6 .then((res) => res.json())
7 .then((data) => setUsers(data));
8 }, []);
9
10 return <p>{users.length} users</p>;
11}
12
13// This API sends back 10 users.
What does the screen show the moment it appears?
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3Why is fetch put inside useEffect and not straight in the component body?
  2. 2 / 3With useState([]) and a fetch in an effect, what does the first screen show?
  3. 3 / 3Why keep a loading state?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Fetching data in React?

09 / 09

Done

You can now
Read a fetch inside useEffect and say what the screen shows before, during and after loading.
Next: Your first Expo app Back to Phase 5
On this page
  1. 01Fetching data in React
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read
Mamun Labs LearnFound a mistake on this page? Tell Mamun.
Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Log in to save your progress. Everything here works without an account.Log in to save progressLog in
Phase 5React
9 topics · 5–6 wks
  1. 1Components and JSX
  2. 2Props
  3. 3State with useState
  4. 4Events in React
  5. 5Showing things conditionally
  6. 6Lists and keys
  7. 7Forms and inputs
  8. 8useEffect
  9. 9Fetching data in React
JourneyPhase 5Fetching data in React
01 / 09Overview

Fetching data in React

You'll learn to load data from an API when a component appears, and show loading, error and data states.

Why it mattersAlmost every app screen shows data from a server, and the same pattern works in React Native.
about 90 min·needs: useEffect, Fetching real data, Loading and error states
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Docs
Synchronizing with effects: fetching datareact.dev · official docs · 10 min · English
MMamun's noteRead the "Fetching data" part only. The ignore flag in the cleanup stops an old answer from replacing a newer one; just notice it for now.
Video
Full React tutorial #17: fetching data with useEffectYouTube · Net Ninja · 8 min · English
MMamun's noteWatch all of it. He fetches from a small local server set up in the video before, but the idea is the same with any URL. Notice the error at 4:02 when the data is still null, and how he fixes it.
VideoOptional
Full React tutorial #19: handling fetch errorsYouTube · Net Ninja · 8 min · English
MMamun's noteAdds an error state and checks res.ok, so a failed request shows a message instead of loading forever.
VideoOptional
4 ways to fetch data from an API in React (Bangla)YouTube · Learn with Sumit · 7 min · Bangla
MMamun's noteIn Bangla. Watch 0:21–7:35, the plain fetch part. The rest shows libraries (axios, react-query) you don't need yet.
03 / 09

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).

Words to recognise
fetchuseEffectloading stateerror state
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

App.jsx6 notes
1import { useEffect, useState } from "react";
2export default function Users() {
3 const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
Mentor note · line 4
Three pieces of state, one for each thing the screen can show. Loading starts as true, because nothing has arrived yet.
5 const [error, setError] = useState(null);
6 useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
8 .then((res) => res.json())
.then((data) => setUsers(data))
10 .catch(() => setError("Could not load users."))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
14 if (error) return <p>{error}</p>;
15 return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
16}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 1
1function Users() {
2 const [users, setUsers] = useState([]);
3
4 useEffect(() => {
5 fetch("https://jsonplaceholder.typicode.com/users")
6 .then((res) => res.json())
7 .then((data) => setUsers(data));
8 }, []);
9
10 return <p>{users.length} users</p>;
11}
12
13// This API sends back 10 users.
What does the screen show the moment it appears?
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3Why is fetch put inside useEffect and not straight in the component body?
  2. 2 / 3With useState([]) and a fetch in an effect, what does the first screen show?
  3. 3 / 3Why keep a loading state?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Fetching data in React?

09 / 09

Done

You can now
Read a fetch inside useEffect and say what the screen shows before, during and after loading.
Next: Your first Expo app Back to Phase 5
On this page
  1. 01Fetching data in React
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read

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).

Words to recognise
fetchuseEffectloading stateerror state

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).

Words to recognise
fetchuseEffectloading stateerror state