Skip to content
Discussion options

You must be logged in to vote

Wrap your async function in useCallback:

const loadData = useCallback(async () => {
  setLoading(true);

  const res = await fetch("/api/data");
  const data = await res.json();

  setItems(data); // updates correctly now
  setLoading(false);
}, []);

This ensures React works with the same stable function reference and doesn’t create stale closures.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by MergenD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Programming Help Discussions around programming languages, open source and software development
3 participants