How to Fetch Data in React with useEffect

Fetching data from an API in a React component using hooks.

When building React apps you will often need to load data from an API when a component first renders. With hooks this is done with the useEffect hook and a little bit of state.

Basic Data Fetching

Here's a component that loads a list of users once when it mounts:

import React, { useState, useEffect } from "react"
function Users() {
const [users, setUsers] = useState([])
useEffect(() => {
async function fetchUsers() {
const res = await fetch("https://jsonplaceholder.typicode.com/users")
const data = await res.json()
setUsers(data)
}
fetchUsers()
}, [])
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
}

The empty array [] at the end tells React to only run the effect once, after the first render.

Why the Async Function Is Inside

You might try to make the effect itself async:

// Don't do this
useEffect(async () => {
...
}, [])

An effect can only return nothing or a cleanup function. An async function always returns a promise, so React will warn you about it. Instead, define an async function inside the effect and call it right away, like in the example above. You can read more about async functions in How to Use async and await in JavaScript.

Adding Loading and Error State

Real requests take time and sometimes fail, so it's worth tracking both:

const [users, setUsers] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
async function fetchUsers() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users")
if (!res.ok) throw new Error("Something went wrong")
setUsers(await res.json())
} catch (error) {
setError(error.message)
} finally {
setLoading(false)
}
}
fetchUsers()
}, [])
if (loading) return <p>Loading...</p>
if (error) return <p>{error}</p>

Note: fetch only rejects on network errors. A 404 or 500 still resolves, so check res.ok yourself.

Refetching When a Prop Changes

If the data depends on a prop, like a user id, put it in the dependency array. The effect will run again whenever it changes:

function User({ id }) {
const [user, setUser] = useState(null)
useEffect(() => {
let ignore = false
async function fetchUser() {
const res = await fetch(
`https://jsonplaceholder.typicode.com/users/${id}`
)
const data = await res.json()
if (!ignore) setUser(data)
}
fetchUser()
return () => {
ignore = true
}
}, [id])
return user ? <h2>{user.name}</h2> : <p>Loading...</p>
}

The cleanup function sets ignore to true when the id changes or the component unmounts. If an old request finishes after a newer one started, its result is ignored instead of overwriting the newer data.

That covers most of the data fetching you'll do in a component. If you end up with a few of these, you can move the logic into a custom hook and reuse it.

Have some feedback on this post? .