Mutation and Optimistic Updates with SWR
Use mutate() and useSWRMutation for write operations with optimistic UI and automatic rollback.
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.
All lessons in this course
- SWR Core Concepts: Stale-While-Revalidate
- useSWR Hook: Fetching, Loading, and Error States
- Mutation and Optimistic Updates with SWR
- SWR vs React Query: Choosing the Right Tool