0Pricing
React Academy · Lesson

Mutation and Optimistic Updates with SWR

Use mutate() and useSWRMutation for write operations with optimistic UI and automatic rollback.

Mutation and Optimistic Updates with SWR is a free React Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

mutate: Revalidating by Key

The global mutate function from swr lets you trigger revalidation for any cache key from anywhere in your application: mutate('/api/user') causes all useSWR('/api/user') hooks to refetch.

Import it with: import { mutate } from 'swr'. This is useful for invalidating data after a server action outside of a component that has direct access to the bound mutate.

mutate with Data: Cache Updates Without Refetch

Pass data as the second argument to mutate: mutate('/api/user', updatedUser) sets the cache to updatedUser immediately without making a network request. This is sometimes called a local mutation.

Add { revalidate: false } as the third argument to prevent SWR from refetching after the optimistic update.

useSWRMutation: For Explicit Triggers

useSWRMutation is designed for user-initiated mutations (form submits, button clicks) as opposed to automatic fetching. It does not run on mount; it runs only when you call trigger().

Import from swr/mutation: const { trigger, isMutating, data, error } = useSWRMutation('/api/post', sendRequest).

useSWRMutation Fetcher Signature

The fetcher for useSWRMutation receives (key, { arg }) where arg is the value passed to trigger(). Example: async (url, { arg: newPost }) => fetch(url, { method: 'POST', body: JSON.stringify(newPost) }).

Call trigger({ title: 'New Post', content: '...' }) to fire the mutation with the post data as the arg.

isMutating State

isMutating from useSWRMutation is true while the mutation request is in flight. Use it to disable submit buttons and show loading spinners during the request, preventing duplicate submissions.

This replaces the manual isSubmitting state variable you would otherwise manage with useState.

Optimistic Updates Explained

An optimistic update immediately applies the expected result to the UI before the server confirms the change. If the server succeeds, nothing more is needed. If it fails, the update is rolled back to the previous state.

This pattern makes UIs feel instantaneous: a like button appears clicked immediately without waiting for the POST response.

Optimistic Updates with SWR

Use mutate(key, newData, { optimisticData: optimisticValue, rollbackOnError: true }). SWR immediately sets the cache to optimisticValue, sends the revalidation request, and rolls back to the previous value if the request throws.

The rollbackOnError: true option is essential for correctness: without it, a failed mutation leaves stale optimistic data in the cache.

Automatic Rollback on Error

When rollbackOnError: true is set and the mutation rejects, SWR automatically restores the cache to the snapshot taken before the optimistic update. No manual rollback code is needed.

Additionally, set populateCache: false if the mutation response body does not match the useSWR data shape, to prevent the response from incorrectly updating the cache.

Bound mutate vs Global mutate

useSWR returns a bound mutate: const { data, mutate } = useSWR('/api/user', fetcher). This bound mutate automatically targets the '/api/user' key; you do not pass the key again.

Use bound mutate inside components that own the data display. Use global mutate from swr when you need to invalidate a key from an unrelated component or utility function.

Comparing to React Query Mutations

React Query's useMutation has a similar trigger/isMutating pattern. Key differences: React Query's onSuccess callback with queryClient.invalidateQueries is the idiomatic cache invalidation pattern. SWR uses the mutate function directly for cache updates.

Both support optimistic updates and rollback, but the API shape differs. Teams proficient in one can learn the other quickly.

Post-Mutation Cache Strategy

After a successful mutation you have three options: refetch by calling mutate(key), update the cache with the response body (if the API returns the updated resource), or combine both with optimistic updates plus revalidation.

For list mutations (adding an item), update the cache manually to append the new item, then revalidate to confirm server state. This avoids a full list refetch while keeping data consistent.

Optimistic Update Rollback

What option must you set in SWR's mutate to automatically revert an optimistic update on error?

Lesson Recap

Global mutate(key) triggers revalidation; mutate(key, data) updates the cache without refetching. useSWRMutation handles explicit user-triggered mutations with trigger(), isMutating state, and extraArg support. Optimistic updates with optimisticData and rollbackOnError: true make UIs feel instant with automatic error recovery.

Bound mutate from useSWR targets its own key; global mutate from swr works anywhere.

Frequently asked questions

Is the “Mutation and Optimistic Updates with SWR” lesson free?

Yes — the full text of “Mutation and Optimistic Updates with SWR” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Mutation and Optimistic Updates with SWR”?

Use mutate() and useSWRMutation for write operations with optimistic UI and automatic rollback. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Mutation and Optimistic Updates with SWR” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. SWR Core Concepts: Stale-While-Revalidate
  2. useSWR Hook: Fetching, Loading, and Error States
  3. Mutation and Optimistic Updates with SWR
  4. SWR vs React Query: Choosing the Right Tool
← Back to React Academy