How to Fetch Data in React With useEffect
SkillVeris Team
Engineering Team

To fetch data in React with useEffect, call your API inside the effect, store the result in state, and track loading and error alongside it.
In this guide, you'll learn:
- Set the dependency array correctly so the fetch re-runs when inputs change and not on every render.
- Always handle three states — loading, error, and success — so the UI never shows stale or broken content.
- Use an AbortController or an ignore flag in the cleanup function to prevent state updates after unmount.
- For anything beyond basic needs, a data library like React Query handles caching, retries, and revalidation for you.
1How to Fetch Data in React With useEffect
To fetch data in React with useEffect, you run your network request inside the effect, save the response into state, and render based on loading, error, and success states. The effect runs after the component mounts, so the UI can show a loading indicator first and then the data once it arrives.
This pattern works because useEffect is designed for side effects — things that reach outside React, like network calls. By pairing the fetch with a dependency array, you control exactly when it re-runs, such as when a search term or an id changes.
2The Basic Pattern
The standard fetch defines an async function inside the effect and calls it immediately. You cannot make the effect callback itself async, because React expects it to return a cleanup function or nothing, not a promise.
- useEffect(() => {
- async function load() {
- const res = await fetch('/api/users');
- const data = await res.json();
- setUsers(data);
- }
- load();
- }, []) # empty array: run once on mount
⚠️Do Not Make the Effect Async
Writing useEffect(async () => ...) returns a promise, which React treats as a cleanup function and warns about. Always define an async function inside and call it.
3Handling Loading and Error States
A real fetch has three outcomes, and a good component renders each one. Skipping loading or error handling leads to blank screens and confusing failures.
- const [data, setData] = useState(null) # the successful result
- const [loading, setLoading] = useState(true) # true until the request settles
- const [error, setError] = useState(null) # holds any thrown error
- Check res.ok and throw on non-2xx responses so failures reach your catch block.
- Render: if loading show a spinner, if error show a message, else show the data.
Wrapping in try/catch/finally
A try block captures the happy path, catch records the error, and finally clears loading regardless of outcome. This guarantees the spinner always disappears.
try { const res = await fetch(url); if (!res.ok) throw new Error(res.status); setData(await res.json()); }
catch (e) { setError(e); }
finally { setLoading(false); }4Dependencies and Cleanup
The dependency array decides when the effect re-runs. Include every value the fetch reads, such as a userId or query, so the data stays in sync when they change. An empty array runs the fetch only once on mount.
Cleanup matters when a component unmounts or the dependency changes before a request finishes. Without it, you may call setState on a gone component or apply a stale response. An AbortController cancels the request, or a simple ignore flag discards the result.
- let ignore = false; # declared at the top of the effect
- if (!ignore) setData(result); # only apply if still relevant
- return () => { ignore = true; }; # cleanup on unmount or re-run
- Or: const ctrl = new AbortController(); fetch(url, { signal: ctrl.signal }); return () => ctrl.abort();
💡Refetch on Input Change
Put the query or id in the dependency array. When it changes, React re-runs the effect automatically, giving you search-as-you-type or detail-page loading for free.
5Common Mistakes to Avoid
Data fetching in useEffect has a handful of classic traps. Avoiding them prevents infinite loops, memory-leak warnings, and race conditions.
- Forgetting the dependency array, so the fetch runs on every render in a loop.
- Putting a new object or function in dependencies, which changes each render and re-triggers the fetch.
- Ignoring cleanup, causing 'state update on unmounted component' warnings and race conditions.
- Not handling errors, so a failed request leaves the UI stuck on the loading state forever.
- Making the effect callback async instead of defining an inner async function.
6When to Reach for a Data Library
Manual useEffect fetching is great for learning and for simple cases, but production apps often need caching, retries, deduplication, and background revalidation. Libraries handle all of this so you write far less boilerplate.
- React Query (TanStack Query): caching, retries, stale-while-revalidate, and devtools.
- SWR: a lightweight hook for fetching with revalidation on focus.
- RTK Query: data fetching integrated with a Redux store.
- Framework loaders: Next.js and Remix fetch on the server before rendering.
🔑Effects Are the Foundation
Even if you adopt a library later, understanding the useEffect pattern teaches you what those tools automate — loading states, cleanup, and dependency-driven refetching.
7Refetching and Dependent Requests
Real apps rarely fetch once. You often need to refetch when a filter changes, retry after a failure, or run a second request that depends on the first. The dependency array handles most of this cleanly.
Put the changing input in the dependency array and React refetches automatically when it changes. For a dependent request — fetching a user, then their orders — gate the second fetch on the first result so it does not fire with an undefined id. A manual refetch button just re-triggers the same loader function.
- useEffect(() => { load(); }, [query]) # refetch when query changes
- Guard dependent calls: if (!userId) return; inside the effect.
- Expose a refetch function by extracting the loader and calling it on demand.
- Debounce fast-changing inputs like search so you do not fire a request per keystroke.
8Key Takeaways
Fetching data in React is straightforward once the pattern clicks. Remember these essentials.
- Call your API inside useEffect via an inner async function, never the effect callback itself.
- Track loading, error, and success state so the UI reflects every outcome.
- List every value the fetch reads in the dependency array to control refetching.
- Clean up with an AbortController or ignore flag to prevent stale updates and leaks.
- Graduate to React Query or SWR when you need caching, retries, and revalidation.
9Frequently Asked Questions
Q: Why can't I make the useEffect callback async? A: React expects the effect callback to return either nothing or a cleanup function. An async function returns a promise, which React cannot use as cleanup and will warn about. Define an async function inside the effect and call it immediately instead.
Q: How do I stop an infinite fetch loop? A: An infinite loop usually means the dependency array is missing or contains a value that changes every render. Provide a stable dependency array, and avoid putting freshly created objects or functions in it without memoization.
Q: How do I cancel a fetch when the component unmounts? A: Return a cleanup function from useEffect that either calls abort on an AbortController tied to the fetch, or sets an ignore flag so the response is discarded. This prevents state updates on unmounted components.
Q: Should I use useEffect or a library like React Query? A: useEffect is perfect for learning and simple one-off fetches. For production apps that need caching, retries, deduplication, and background refresh, a library like React Query or SWR removes most of the boilerplate and edge cases.
Related Reading
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.