Skip to main content

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: true and suspense: true in the useMutation options. 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 handling
    const { mutate } = useMutation({
    suspense: true,
    errorBoundary: true
    });

    const onSave = () => {
    mutate(() => api.save(data));
    };
  • Best Practice: Use errorBoundary: true to handle mutation errors centrally using an Error Boundary, reducing the need for local try...catch blocks or explicit error checks. This promotes a more declarative and robust error-handling strategy. Always ensure a parent ErrorBoundary exists 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:

  1. User clicks savemutate() is called.
  2. Mutation fails → The action function throws an error.
  3. useMutation catches the error → It stores it in the mutateCache.
  4. useMutation re-throws the error → During the next render cycle, the hook throws the error object.
  5. The nearest ErrorBoundary catches it → Stops rendering ProfileForm.
  6. <ErrorDisplay /> is rendered → Fallback shows instead of the form.
  7. ErrorDisplay provides a retry mechanism → By calling resetError() on the DataClient or via another method.

What happens step by step without errorBoundary:

  1. User clicks savemutate() is called.
  2. Mutation fails → The action function throws an error.
  3. useMutation catches the error → It stores it in the cache and local state.
  4. useMutation returns { error: Error, ... } → No error is thrown to React.
  5. Component continues to render → Must manually check and display the error.
  6. 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.