Loading Data in an Effect

Load a user when the component appears and again when the id changes, and ignore answers that arrive too late.

React · beginner · 9 min · 44 steps · free

What you'll learn

FetchingData.jsx

import { useState, useEffect } from 'react';

// Stands in for a real request: answers after half a second.
function fetchUser(id) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id, name: id === 1 ? 'Ada' : 'Linus' }), 500);
  });
}

export default function UserCard() {
  const [userId, setUserId] = useState(1);
  const [user, setUser] = useState(null);

  useEffect(() => {
    let ignore = false;
    fetchUser(userId).then((data) => {
      if (!ignore) setUser(data);
    });
    return () => {
      ignore = true;
    };
  }, [userId]);

  return (
    <div>
      {user ? <h3>{user.name}</h3> : <p>Loading…</p>}
      <button onClick={() => setUserId(userId === 1 ? 2 : 1)}>Next user</button>
    </div>
  );
}

Step by step

  1. React renders <UserCard> for the first time: it calls the UserCard function.
  2. useState runs for the first time, so React stores the starting value for userId and returns it: 1.
  3. useState runs for the first time, so React stores the starting value for user and returns it: null.
  4. useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.
  5. UserCard returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  6. The first render shows "Loading…": user is still null.
  7. Now the effect starts the request for user 1.
  8. ignore starts false. The cleanup will set it to true if this request becomes out of date.
  9. Runs setTimeout(() => resolve({ id, name: id === 1 ? 'Ada' : 'L….
  10. fetchUser returns a Promise straight away. The answer comes later.
  11. Runs fetchUser(userId).then((data) => { if (!ignore) setUser(da….
  12. The effect returns its cleanup and finishes. The page still says Loading….
  13. Half a second later the answer arrives: { id: 1, name: "Ada" }.
  14. ignore is still false, so setUser(data) stores the user.
  15. React renders <UserCard> again (render 2): it calls UserCard once more, from the top.
  16. useState returns the value React has kept for userId: 1. The starting value is only used on the first render.
  17. useState returns the value React has kept for user: { id: 1, name: "Ada" }. The starting value is only used on the first render.
  18. useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.
  19. UserCard returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  20. Ada is on the page.
  21. You click the “Next user” button. React calls its onClick handler.
  22. setUserId(userId === 1 ? 2 : 1) does not change userId right away: React queues the update and will render again. In this call userId is still 1.
  23. React renders <UserCard> again (render 3): it calls UserCard once more, from the top.
  24. useState returns the value React has kept for userId: 2. The starting value is only used on the first render.
  25. useState returns the value React has kept for user: { id: 1, name: "Ada" }. The starting value is only used on the first render.
  26. useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.
  27. UserCard returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  28. React compares the new JSX with the last one. Nothing on screen changed, so it leaves the page alone.
  29. userId changed, so before running the effect again React calls the cleanup from the last run.
  30. ignore is now true for the old request.
  31. The effect runs again, for user 2.
  32. ignore = false.
  33. Runs setTimeout(() => resolve({ id, name: id === 1 ? 'Ada' : 'L….
  34. fetchUser returns Promise (pending).
  35. Runs fetchUser(userId).then((data) => { if (!ignore) setUser(da….
  36. The effect returns a cleanup function. React keeps it to call later.
  37. It runs resolve({ id, name: id === 1 ? 'Ada' : 'Linus' }).
  38. !ignore is true, so the if-block runs.
  39. React renders <UserCard> again (render 4): it calls UserCard once more, from the top.
  40. useState returns the value React has kept for userId: 2. The starting value is only used on the first render.
  41. useState returns the value React has kept for user: { id: 2, name: "Linus" }. The starting value is only used on the first render.
  42. useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.
  43. UserCard returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  44. Linus is on the page.

Common mistakes

Best practices

Key takeaways

Check yourself

Why ignore = true in the cleanup?

Answer: So an old answer cannot overwrite newer data. The request still finishes; its result is ignored.

Why not useEffect(async () => …)?

Answer: An async function returns a Promise, not a cleanup

·

More in Effects and Refs