errorBoundary
Description: Defines if the error should be thrown. The suspense property has to be true in order for this to work.
- How To: Pass
errorBoundary: trueandsuspense: truein theuseMutationoptions. If an error occurs during mutation, it will be thrown and can be caught by a React Error Boundary.// Correct: Enable Error Boundary for centralized mutation error handlingconst { mutate } = useMutation({suspense: true,errorBoundary: true});const onSave = () => {mutate(() => api.save(data));}; - Best Practice: Use
errorBoundary: trueto handle mutation errors centrally using an Error Boundary, reducing the need for localtry...catchblocks or explicit error checks. This promotes a more declarative and robust error-handling strategy. Always ensure a parentErrorBoundaryexists in your component tree when using this option.
Deep Dive: How errorBoundary works step by step
Example:
function ProfileForm() {
const { mutate } = useMutation({
suspense: true,
errorBoundary: true
});
return <button onClick={() => mutate(saveAction)}>Save Profile</button>;
}
<ErrorBoundary fallback={<ErrorDisplay />}>
<ProfileForm />
</ErrorBoundary>
What happens step by step with errorBoundary: true:
- User clicks save →
mutate()is called. - Mutation fails → The action function throws an error.
useMutationcatches the error → It stores it in themutateCache.useMutationre-throws the error → During the next render cycle, the hook throws the error object.- The nearest
ErrorBoundarycatches it → Stops renderingProfileForm. <ErrorDisplay />is rendered → Fallback shows instead of the form.ErrorDisplayprovides a retry mechanism → By callingresetError()on theDataClientor via another method.
What happens step by step without errorBoundary:
- User clicks save →
mutate()is called. - Mutation fails → The action function throws an error.
useMutationcatches the error → It stores it in the cache and local state.useMutationreturns{ error: Error, ... }→ No error is thrown to React.- Component continues to render → Must manually check and display the
error. - You must handle the error UI → Explicitly show an error message in your component.
Key insight: The errorBoundary option works in tandem with suspense to provide a declarative way of handling failures, treating mutation errors similarly to regular JavaScript errors that bubble up the component tree.