Fetching Data
Fetching data loads data from a server after mount. Fetch is a function that asks a server for data.
Ask for data
The effect asks the server once after mount.
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://example.com/api/users').then((r) => r.json()).then((data) => setUsers(data));
}, []);
return <p>{users.length} users.</p>;The first render
Zero users show the loading message.
const [users, setUsers] = useState([]);
return <p>{users.length === 0 ? 'Loading...' : 'Loaded.'}</p>;Example
import { useState, useEffect } from 'react';
export default function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://example.com/api/users')
.then((response) => response.json())
.then((data) => {
setUsers(data);
setLoading(false);
});
}, []);
if (loading) {
return <p>Loading...</p>;
}
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Key points
- Fetch runs inside a useEffect, so it runs after mount.
- A promise is a value that arrives later.
- Fetch returns a promise.
- The then method runs when the data arrives.
- The json method reads the body as a JavaScript value.
- The data goes into state, so the page updates when it arrives.
- The effect runs once when the dependency list is empty.
In this example, the users state value starts as an empty array. The loading state value starts as true. The effect runs after mount and asks the server for users. The first render shows Loading because the effect has not run yet. When the data arrives, the effect stores it and sets loading to false. The list then shows one item per user.
Note
The first render shows before the data arrives, so it needs a loading message.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does fetch run when loading data for a component?