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.
Use invalidateQuery on the QueryClient.
// Invalidate a specific queryclient.invalidateQuery('todos'.toQueryKey());
// The next time 'todos' is accessed (or immediately if active),// it will refetch from the server.| Method | Description |
|---|---|
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
Section titled “Examples”Post-Mutation Invalidation
Section titled “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
Section titled “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
Section titled “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);