advanced

Cache invalidation

Connect writes to the cached reads they affect using keys, tags, dependency graphs, and product freshness rules.

Invalidation connects writes to the reads they affect. Strategies: key prefix invalidation, exact key match, tag graphs (RTK Query), or manual `setQueryData` when you know the next shape.

					// After creating a post, invalidate list and prime detail cache
queryClient.invalidateQueries({ queryKey: ['posts'] });
queryClient.setQueryData(['posts', newPost.id], newPost);
				

| Strategy | When | |----------|------| | Broad invalidate | Simple apps; tolerate refetch cost | | Targeted keys | Known affected queries only | | setQueryData | Server response matches cache shape | | Optimistic + rollback | Latency-sensitive UX |

Product rules define freshness: dashboards may poll; reference data may live minutes; user-specific data refetches on navigation.

On interviews: hardest problem quote — name your key/tag scheme before coding mutations.

Common pitfalls: invalidate everything on every POST, stale detail after list update, and racing refetch with optimistic UI.

Checklist:

  • Document key hierarchy and dependencies.
  • Invalidate smallest sufficient set.
  • Update cache directly when response is authoritative.
  • Test concurrent mutations and failures.