Course contentsShow
← React
Lesson 1801 of 2,39642. Data Fetching LibrariesFree lesson

Global Mutation Defaults

Configure default mutation behavior (retries, cache time, callbacks) in the QueryClient for consistency across mutations.

Global Mutation Defaults

You'll learn how to configure default behavior for all mutations in your app at once, rather than repeating the same options in every useMutation call.

The Repetition Problem

If you find yourself typing the same mutation options repeatedly—retry: 3, onError: logError, or specific cache settings—across dozens of useMutation hooks, you're duplicating configuration. Every mutation retrying three times, every mutation logging errors the same way, every mutation needing the same cleanup logic.

Configuring Mutation Defaults

When you create your QueryClient, you can set global mutation defaults that apply to every mutation unless explicitly overridden:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient({
  defaultOptions: {
    mutations: {
      retry: 2,
      cacheTime: 1000 * 60 * 5, // 5 minutes
      onError: (error) => {
        console.error('Mutation failed:', error);
        // Global error handling
      },
      onSettled: () => {
        // Global cleanup logic
      },
    },
  },
});

Now every useMutation in your app automatically retries twice, caches for 5 minutes, and logs errors—without rewriting those lines.

When to Use Per-Mutation Overrides

Individual mutations can still override these defaults. If one mutation shouldn't retry, just specify retry: false in that specific useMutation call. The global defaults act as a baseline, not a prison.

Why This Matters

Think of it like setting default font styles in CSS—you establish consistency across your app, reduce boilerplate, and ensure mutations behave predictably. Changing one line in your QueryClient updates behavior everywhere instantly.

Key Takeaway: Global mutation defaults in the QueryClient establish consistent retry, caching, and callback behavior across all mutations, eliminating repetitive configuration while allowing per-mutation overrides when needed.