Async & APIIntermediateSSR-safehooks/async/useMutation.ts

useMutation

POST/PUT style mutations.

Import

TypeScript
import { useMutation } from '@/hooks';

API

Signature

useMutation(mutationFn, options?) → { mutate, isLoading, ... }

When to use

Use useMutation instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-side. Prefer RSC for first-paint server data.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useMutation
Editor
function CreatePost() {
  const { mutate, isLoading, isError } = useMutation(async (title: string) => {
    const res = await fetch('/api/posts', {
      method: 'POST',
      body: JSON.stringify({ title }),
    });
    return res.json();
  });

  return (
    <button disabled={isLoading} onClick={() => void mutate('Hello')}>
      {isLoading ? '…' : isError ? 'Retry' : 'Create'}
    </button>
  );
}
Preview

Implementation source

Full library source for useMutation — copy into your project when you are not installing a package yet.

hooks/async/useMutation.ts
import { useAsyncFn } from './useAsyncFn';

export interface UseMutationOptions<TData, TVariables> {
  onSuccess?: (data: TData, variables: TVariables) => void;
  onError?: (error: Error, variables: TVariables) => void;
}

/**
 * Generic mutation helper (POST/PUT/PATCH style operations).
 */
export function useMutation<TData = unknown, TVariables = void>(
  mutationFn: (variables: TVariables) => Promise<TData>,
  options: UseMutationOptions<TData, TVariables> = {},
) {
  const [state, execute] = useAsyncFn(
    async (variables: TVariables) => {
      try {
        const data = await mutationFn(variables);
        options.onSuccess?.(data, variables);
        return data;
      } catch (error) {
        const err = error instanceof Error ? error : new Error(String(error));
        options.onError?.(err, variables);
        throw err;
      }
    },
    [mutationFn],
  );

  return {
    ...state,
    mutate: execute,
    mutateAsync: execute,
    isLoading: state.loading,
    isError: state.status === 'error',
    isSuccess: state.status === 'success',
  };
}

Copy-paste example

useMutation.example.tsx
'use client';

import { useMutation } from '@/hooks';

export function CreatePost() {
  const { mutate, isLoading, isError } = useMutation(async (title: string) => {
    const res = await fetch('/api/posts', {
      method: 'POST',
      body: JSON.stringify({ title }),
    });
    return res.json();
  });

  return (
    <button disabled={isLoading} onClick={() => void mutate('Hello')}>
      {isLoading ? '…' : isError ? 'Retry' : 'Create'}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
  • Source of truth: open hooks/async/useMutation.ts for implementation details