← Lessons

quiz vs the machine

Gold1360

Frontend

The Cache Invalidation in Query Libs

Mark cached data as stale after writes so the library refetches and screens show fresh server state.

5 min read · core · beat Gold to climb

The problem invalidation solves

A query library caches server data by key, which makes reads fast but creates a risk: after a write, the cache still holds the old value. Cache invalidation is how you tell the library that a key is now stale so it refetches the truth from the server.

  • A successful mutation often changes data behind one or more keys.
  • Without invalidation the screen keeps showing the pre write value.
  • Invalidation marks keys stale and triggers a background refetch.

Invalidate by key and scope

You usually invalidate by key, and good keys are structured so you can invalidate a whole group at once.

  • Use hierarchical keys like a list key plus item keys so you can clear a family.
  • Invalidate the narrowest scope that covers what changed to avoid over fetching.
  • Prefer invalidation over manually editing the cache when the server is the source of truth.

Refetch versus remove

Invalidation does not always fetch immediately. Often it marks data stale and refetches only the queries that are currently mounted, while unmounted ones refetch when next used. That keeps invalidation cheap.

Key idea

After a write, invalidate the affected query keys so the library marks them stale and refetches, keeping the screen consistent with the server.

Check yourself

Answer to earn rating on the learn ladder.

1. What does invalidating a query key do?

2. Why are hierarchical query keys useful for invalidation?

3. When does invalidation typically trigger an immediate refetch?