# Data Fetching & Caching

> Why fetching data inside useEffect is a bad idea, and how modern caching libraries (like React Query or SWR) solve it.

Subject: React | Lesson 27 of 48 | 4 min read
Interactive lesson: https://codewithanimation.in/react/data-fetching-caching
Previous: [Client vs. Server State](https://codewithanimation.in/react/client-vs-server-state.md) | Next: [Global State Management](https://codewithanimation.in/react/global-state-management.md)

## The useEffect Trap

In the past, fetching data in React involved a standard boilerplate: setting up three state variables (`data`, `isLoading`, `error`), writing a `useEffect`, calling `fetch()`, and manually updating those state variables.

This approach is now considered an anti-pattern for production apps. It causes a 'waterfall' of loading spinners, it doesn't cache data (if you leave the page and come back, you see a spinner again), and it doesn't deduplicate requests (if two components need the same data, you fetch it twice).

## Enter Caching Libraries

Modern React uses libraries like **TanStack Query (React Query)** or **SWR**.

Instead of manually managing state, you provide a 'Query Key' (like `['users']`) and an async function. The library handles the rest.

If you ask for `['users']` in five different components, the library merges them into a *single* network request and shares the cached result with all five.

## How it works under the hood

These libraries maintain a global cache outside of the React component tree.

When a component mounts, it subscribes to a specific cache key.

If the data is in the cache, it is returned instantly (no loading spinner). In the background, the library quietly re-fetches the data to see if it has changed (called 'stale-while-revalidate'). If it has, it seamlessly updates the UI.

## Common mistake: Race Conditions and Cleanup

Writing a safe `fetch` inside `useEffect` is surprisingly difficult.

If a user clicks a button fast enough to trigger two fetches, the first fetch might resolve *after* the second fetch, overwriting the new data with old data (a race condition).

To fix this in vanilla React, you must use an `AbortController` or an `ignore` boolean flag inside the `useEffect` cleanup function. Caching libraries handle these race conditions automatically.

## Tip: Mutations and Invalidations

When you send data to the server (e.g., adding a new user), you perform a 'Mutation'.

Instead of manually updating the local state, you simply tell the cache to 'invalidate' the `['users']` key. The library will automatically re-fetch the list, keeping your UI perfectly in sync with the database.

## Try it: Deduplication & Caching

Watch how a modern caching layer deduplicates multiple simultaneous requests, and how it instantly serves cached data on subsequent visits.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/data-fetching-caching

## Check yourself

### Question 1

If three separate components call `useQuery({ queryKey: ['posts'], ... })` at exactly the same time, how many network requests are made?

- A. Three, because they are separate components.
- B. One. The library deduplicates the requests and shares the result.
- C. Zero, it waits for a user interaction.

Correct answer: B

Caching libraries use the Query Key to identify identical requests and merge them into a single network call.

- Why not A: This is what happens with standard `useEffect`, but not with React Query.
- Why not C: Queries fire immediately on mount by default.

### Question 2

What does the 'Stale-While-Revalidate' caching strategy do?

- A. It prevents any network requests if data exists in the cache.
- B. It instantly shows the user the cached (stale) data, while secretly re-fetching fresh data in the background.
- C. It deletes stale data and shows a loading spinner until fresh data arrives.

Correct answer: B

This strategy provides the illusion of instantaneous loading times while still ensuring the data stays up to date.

- Why not A: It still makes network requests in the background.
- Why not C: That would ruin the user experience by showing constant loading spinners.

### Question 3

Why is a raw `fetch` inside a `useEffect` prone to race conditions?

- A. Because `fetch` is synchronous and blocks the main thread.
- B. Because if two requests fire in sequence, the first request's promise might resolve AFTER the second request's promise.
- C. Because React re-renders too quickly for the network.

Correct answer: B

Network latency is unpredictable. Request A might take 2 seconds, while Request B takes 0.5 seconds. If not handled carefully, Request A will arrive last and overwrite the newer data from Request B.

- Why not A: `fetch` is asynchronous.
- Why not C: It's an issue with the unpredictable speed of network requests, not React.

## Remember this

- Fetching data directly inside `useEffect` is an anti-pattern for production.
- Caching libraries (React Query, SWR) deduplicate requests based on a Query Key.
- They use a global cache to eliminate unnecessary loading spinners.
- The 'Stale-While-Revalidate' strategy shows old data instantly while fetching new data silently.
- They automatically handle race conditions, retries, and cache invalidation.
