Blog>
Snippets

Manual Cache Updates after Mutation

Demonstrate how to manually update the cache after a mutation to keep data synchronized across the application without refetching.
const [mutatePost] = useMutation(updatePost, {
  onSuccess: (updatedPost) => {
    queryClient.setQueryData(['post', updatedPost.id], updatedPost);
  }
});
This code defines a mutation using a `useMutation` hook from a library like React Query. After the `updatePost` mutation succeeds, the `onSuccess` callback updates the cached data for a specific post using `setQueryData`, ensuring the UI reflects the latest changes without needing to refetch.
queryClient.invalidateQueries('posts');
After a successful mutation, this line of code manually invalidates the cache for all queries with the 'posts' key. This triggers a refetch of posts data to ensure that any component using this data stays in sync with the latest state.