Skip to main content

MutationObserver

The MutationObserver class is used to observe mutations and subscribe to changes in mutation state. This is the core class that powers useMutation in framework integrations.

Import

Constructor

Type Parameters

type
default:"unknown"
The type of data returned by the mutation function
type
default:"DefaultError"
The type of error that can be thrown
type
default:"void"
The type of variables passed to the mutation function
type
default:"unknown"
The type of context returned by onMutate

Parameters

QueryClient
required
The QueryClient instance to use
MutationObserverOptions
required
Configuration options for the mutation observer
(variables: TVariables) => Promise<TData>
required
The function that performs the mutation
MutationKey
Optional unique key for the mutation
(variables: TVariables) => Promise<TContext> | TContext
Callback fired before mutation function is executed
(data: TData, variables: TVariables, context: TContext) => Promise<unknown> | unknown
Callback fired when mutation succeeds
(error: TError, variables: TVariables, context: TContext | undefined) => Promise<unknown> | unknown
Callback fired when mutation errors
(data: TData | undefined, error: TError | null, variables: TVariables, context: TContext | undefined) => Promise<unknown> | unknown
Callback fired when mutation completes (success or error)
boolean | number | (failureCount: number, error: TError) => boolean
default:"0"
Number of retry attempts or function to determine retries
number | (failureCount: number, error: TError) => number
Delay between retry attempts

Methods

mutate

Execute the mutation with the given variables.

reset

Reset the mutation observer to its initial state.

setOptions

Update the mutation observer options.

subscribe

Subscribe to mutation state changes. Returns an unsubscribe function.

getCurrentResult

Get the current mutation result.

Result Type

Examples

Basic Usage

With Callbacks

Multiple Subscribers

Updating Options

Manual State Management

With Retry Logic

Notes

  • MutationObserver is the low-level class that framework integrations build upon
  • In React, useMutation creates and manages a MutationObserver instance
  • Observers can have multiple subscribers
  • The observer manages a single mutation instance at a time
  • Calling mutate() multiple times creates new mutation instances
  • Each mutation instance has its own state and lifecycle
  • The observer automatically handles retry logic based on configuration
  • Subscribers are notified synchronously when state changes