How to invalidate queries in React Query
Query invalidation in React Query forces refetching of stale data after mutations, ensuring the UI stays synchronized with server state without manual cache updates. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented query invalidation patterns in admin dashboards throughout my 11 years of React development. The most reliable approach is using queryClient.invalidateQueries in mutation callbacks to automatically refetch affected data. This method maintains data consistency across components without complex state synchronization logic.
Use queryClient.invalidateQueries in mutation onSuccess callback to refetch affected queries.
import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query'
const AddUser = () => {
const queryClient = useQueryClient()
const addUserMutation = useMutation({
mutationFn: async (newUser) => {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
})
return response.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] })
}
})
const handleAdd = () => {
addUserMutation.mutate({ name: 'John Doe', email: '[email protected]' })
}
return (
<button onClick={handleAdd} disabled={addUserMutation.isPending}>
Add User
</button>
)
}
Here useMutation handles the POST request to create a new user. The onSuccess callback fires when the mutation completes successfully, calling queryClient.invalidateQueries with the queryKey [‘users’]. This marks all queries matching that key as stale, triggering automatic refetches in components using those queries. Any UserList component with useQuery({ queryKey: [‘users’] }) will immediately refetch, displaying the newly added user without manual state updates.
Best Practice Note:
This is the pattern we use in CoreUI admin panels for consistent data synchronization across CRUD operations. Invalidate specific queries by exact keys or use partial matching with queryKey: [‘users’, userId] patterns, consider optimistic updates for better UX, and invalidate related queries together to maintain referential integrity across the application.



