Fetch a user from the server, then show their name. It sounds like one line of code. But try writing user.name on the first render: the page crashes, because the data hasn't arrived yet.
Data from a server isn't there right away. The component shows first, then a request goes out to the server. The answer arrives a little later, or the request fails. It's like ordering food in an app. After you order, the screen says "order in progress". Then the food arrives, or you get "order failed". A component that fetches data has to be ready for the same three states: loading (waiting, like "order in progress"), data (it worked, the food arrived), and error (it failed, like "order failed").
Three states: loading, error, data
A component that fetches data usually keeps three pieces of state:
| State | Starts as | Meaning |
|---|---|---|
loading |
true |
the request is still running, no answer yet |
error |
null |
a message if it failed, null if nothing went wrong |
user |
null |
the data, filled in once the answer arrives |
loading starts as true, because on the first render there really is no data yet. If it started as false, the component would go straight to showing user.name. But user is still null, so the page would crash.
Fetch the data in useEffect
Fetching data is a side effect. It belongs in useEffect, not directly in the component body. The body runs on every render, so a fetch there sends a new request on every render.
Here is a UserCard component that fetches the data of one user:
function UserCard({ userId }) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
setLoading(true)
setError(null)
async function load() {
try {
const res = await fetch(`/api/users/${userId}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
setUser(data)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}
load()
}, [userId])
if (loading) return <p>Loading...</p>
if (error) return <p>Failed to load: {error}</p>
return <p>{user.name}, {user.city}</p>
}
useEffect(..., [userId])runs after the first render, then again every timeuserIdchanges. With[], the effect runs only once, after the component first shows.async function load()is made inside the effect, then called right away. The next section explains why.res.okisfalsewhen the server answers 404 (the data wasn't found) or 500 (the server has a problem).fetchdoesn't treat that answer as a failure. So this code throws an error itself withthrow, to jump tocatch.res.json()reads the body of the answer and turns it into an object. With.then, it looks like.then(res => res.json()).finallyruns on success and on failure alike, soloadingalways goes back tofalse.- The last three lines pick what to show, in order: loading first, then the error, and only then the data.
This is the order of events in the Lab for userId = 2, on a normal network (the answer arrives in 500 ms):
| Time | What happens | loading |
error |
user |
Shown |
|---|---|---|---|---|---|
| 0 ms | first render | true |
null |
null |
Loading... |
| 0 ms | the effect runs, a request to /api/users/2 goes out |
true |
null |
null |
Loading... |
| 500 ms | the answer arrives, setUser then setLoading(false) |
false |
null |
Budi | Budi, Manchester |
If you turn on "Server error" in the Lab, the server answers 500. res.ok becomes false, the code throws, and you see Failed to load: HTTP 500.
Why the useEffect callback can't be async
This code looks shorter, but it's wrong:
// ❌ wrong
useEffect(async () => {
const data = await fetchData()
setData(data)
}, [])
An async function always returns a Promise. But a useEffect callback may only return one of two things: nothing at all, or a cleanup function. React would treat that Promise as a cleanup, then warn you. So make an async function inside the effect and call it, like load() in UserCard.
Switching users quickly
You saw this problem in the useEffect in Depth lesson (a race condition): the answer to an old request that arrives late can overwrite the new answer. Say the answer for Andi takes 2.4 seconds, and the answer for Budi takes 0.8 seconds. You click Andi, then Budi:
| Time | Event | Shown |
|---|---|---|
| 0 s | click Andi, a request to /api/users/1 goes out |
Loading... |
| 0.2 s | click Budi, a request to /api/users/2 goes out |
Loading... |
| 1.0 s | Budi's answer arrives | Budi, Manchester |
| 2.4 s | Andi's answer arrives late, setUser runs |
Andi, London |
You picked Budi, but you see Andi. The guard against this problem is one ignore variable and a cleanup:
useEffect(() => {
let ignore = false
setLoading(true)
setError(null)
async function load() {
try {
const res = await fetch(`/api/users/${userId}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
if (!ignore) setUser(data)
} catch (err) {
if (!ignore) setError(err.message)
} finally {
if (!ignore) setLoading(false)
}
}
load()
return () => { ignore = true }
}, [userId])
- When
userIdchanges, React first runs the cleanup of the old effect. That cleanup makes theignoreof Andi's requesttrue. - Andi's answer still arrives, but every
set...is skipped. Budi stays on screen. AbortControlleris another way: the old request is actually cancelled, not just ignored.
📌 In a real app: TanStack Query
You need to understand the useEffect pattern above. But writing it in every component is tiring. And a lot is still missing: a cache (data you've fetched is kept, so you don't ask for it again), trying again after a failure, and fetching again when the tab is opened again. In real apps, people usually use a data library such as TanStack Query. BelajarWeb.dev uses it too. Here is the same UserCard, written with useQuery from TanStack Query:
async function getUser(userId) {
const res = await fetch(`/api/users/${userId}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
function UserCard({ userId }) {
const { data: user, isLoading, error } = useQuery({
queryKey: ["user", userId],
queryFn: () => getUser(userId),
})
if (isLoading) return <p>Loading...</p>
if (error) return <p>Failed to load: {error.message}</p>
return <p>{user.name}, {user.city}</p>
}
There are still three states: isLoading, error and data. The difference is that the library handles the useEffect, the ignore and the three useStates. queryFn is the function that fetches the data, here getUser. queryKey is the data's name in the cache. The library only shows the answer for the key in use, so the late-answer problem is solved too. To make useQuery work, you wrap the whole app in a QueryClientProvider once, in the top component.
Other options for getting data:
| Way | When to pick it |
|---|---|
useEffect with fetch |
Learning, or one small part of a page. This lesson starts here so that you see every step. |
| TanStack Query or SWR | A single-page app with lots of data from a server. The cache, retries and fetching again are handled for you. |
A loader in React Router, or a Server Component in Next.js |
An app built with a framework. The framework gets the data before the component shows. |
The React docs (react.dev) suggest this order. Use the framework's own way if there is one. If not, use a library such as TanStack Query. Use useEffect when neither fits.
⚠️ Requests that never stop, and errors that are never caught
- Fetching straight in the component body. Every render sends a request. The answer calls
setState,setStatecauses a render, and that render sends a request again: a loop that never ends. Put it inuseEffect. - Forgetting the dependency array.
useEffect(() => { ... })with no array runs after every render, which is no better than fetching in the body. Use[]to run it only once, or[userId]to run it again every time the id changes. - Not checking
res.ok. A 404 answer gets processed as if the data were there. - Putting the data in as the state's starting value.
useState(["Andi", "Budi"])fetches nothing from the server. Server data only exists after the request finishes. So in the second exercise, fill the state withsetUsers(...)inside the effect.
TL;DR: Server data arrives later, so a component needs three states: loading (waiting, starts true), error (a message if it failed, starts null), and the data. Fetch in useEffect, with [] to run it only once, or [userId] to run it again every time userId changes. The useEffect callback can't be async: make an async function inside it, then call it. Check res.ok, because fetch doesn't treat 404 and 500 answers as failures. Read the body with res.json(), and turn loading off in finally. If the id can change quickly, add let ignore = false and a cleanup that sets ignore = true, so a late answer can't overwrite the new one. In real apps, a library such as TanStack Query handles all of this, plus a cache (data you've fetched is kept).
⚡ Three states
Meaning: Data from a server arrives a little after the component shows, or never arrives because the request failed. So a component needs three pieces of state: loading (waiting, starts true), error (a message if it failed, starts null), and the data. What shows is picked in order: loading first, then the error, and only then the data.
⚡ Fetch the data, catch the error
Write:
try {
const res = await fetch(`/api/users/${userId}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
setUser(data)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
Guess first: the server answers 404 or 500. Does fetch treat that as a failure?
No. res.ok becomes false, but fetch doesn't treat it as a failure. That's why this code throws an error itself with throw, to jump to catch.
Meaning: This code runs inside useEffect. fetch sends the request, res.json() turns the body of the answer into an object, and setUser keeps it. If there's an error, catch keeps its message with setError. finally runs on success and on failure alike, so loading always goes back to false.
⚡ A useEffect callback can't be async
Write:
// ❌ wrong
useEffect(async () => {
const data = await fetchData()
setData(data)
}, [])
Guess first: why does React warn about the code above?
An async function always returns a Promise, but a useEffect callback may only return a cleanup function or nothing at all.
Meaning: Make an async function inside the effect, then call it right away. For example, async function load() inside the effect, then load() right below it.