CLOSE
Introduction
In this post, you'll learn how to use an async function inside your React useEffect hook.
Below, we set up some initial state with useState, which we want to populate with a GET request when the component mounts.
const Users = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetchUsers().then((users) => setUsers(users));
}, []);
if (!users) return <div>Loading...</div>;
return (
<ul>
{users.map((user) => (
<li>{user.name}</li>
))}
</ul>
);
};
Using async directly in useEffect has issues:
// ❌ Don't do this!
useEffect(async () => {
const users = await fetchUsers();
setUsers(users);
}, []);
Instead, use an async function inside useEffect correctly:
// ✅ Do this
useEffect(() => {
(async () => {
const users = await fetchUsers();
setUsers(users);
})();
return () => {
// function
};
}, []);
Or with a named function:
// ✅ Or do this
useEffect(() => {
const getUsers = async () => {
const users = await fetchUsers();
setUsers(users);
};
getUsers();
return () => {
// function
};
}, []);
Both methods ensure the cleanup function is called correctly. Now you can safely use async functions in useEffect.
Happy coding!