Skip to Content

Cache Invalidation

Invalidation is the process of marking data as “stale” so it gets refetched. This is critical for keeping your UI in sync with the server after mutations.

Usage

Use invalidateQuery on the QueryClient.

// Invalidate a specific query client.invalidateQuery('todos'.toQueryKey()); // The next time 'todos' is accessed (or immediately if active), // it will refetch from the server.

API

MethodDescription
invalidateQuery(key)Marks a specific query as stale.
invalidateQueries(keys)Invalidates a list of keys.
invalidateQueriesWithPrefix(prefix)Invalidates all keys starting with the prefix.

Examples

Post-Mutation Invalidation

The most common pattern: update data -> invalidate list -> list refreshes.

MutationBuilder( mutationFn: (newTodo) => api.addTodo(newTodo), options: MutationOptions( onSuccess: (_) { // User added a todo, so the list is now outdated. // Invalidate it to trigger a refetch. QueryClient().invalidateQuery('todos'.toQueryKey()); }, ), // ... )

Prefix Invalidation

Invalidate a group of related queries.

// Invalidate 'projects', 'projects:1', 'projects:archived', etc. QueryClient().invalidateQueriesWithPrefix('projects');

This requires you to structure your keys hierarchically (e.g. using colons projects:1).

Invalidate Active vs Inactive

By default, invalidation affects all queries.

  • Active queries (currently used on screen) will refetch immediately in the background.
  • Inactive queries (not on screen) are just marked stale and will refetch next time they are used.

You can customize this behavior:

client.invalidateQuery( 'todos'.toQueryKey(), refetchType: InvalidateType.active, // Only refetch if currently visible );
Last updated on