Data loading

Loading data in useEffect requires handling loading and error, and ignoring a response that arrives after unmounting or after a parameter change. You cancel the request in the cleanup function with AbortController, and put the parameter in the dependencies.

Example

useEffect(() => {
  const c = new AbortController();
  fetch(url, { signal: c.signal }).then(r => r.json()).then(setData);
  return () => c.abort();
}, [url]);

Related concepts

The whole glossary