Blog>
Snippets

Query Invalidation and Refetching

Explain how to invalidate and refetch queries with React Query after a mutation, using a practical example where updating user information requires refreshing the user list displayed on the screen.
import { useMutation, useQueryClient } from 'react-query';
First, import useMutation and useQueryClient from react-query to be able to perform mutations and access the query client for cache operations.
const queryClient = useQueryClient();
Initialize the query client inside your component to interact with the React Query cache.
const updateUser = async (userData) => {
  // API call to update user data
};
Define an asynchronous function to update user data through an API call. This will be used in the mutation.
const { mutate } = useMutation(updateUser, {
  onSuccess: () => {
    queryClient.invalidateQueries('users');
  }
});
Use useMutation hook to call the updateUser function. On success of the mutation, invalidate the 'users' query to refetch the updated list of users.
mutate(newUserDetails);
Trigger the mutation with the new user details. This updates the user on the server and then invalidates the users query to refetch the updated list.