Revalidation After Mutations
What you'll learn: How to refresh cached data after successfully modifying it through Server Actions.
The Problem: Stale Data After Changes
When you mutate data on the server (create, update, or delete), React's cache still holds the old version. Users won't see their changes reflected unless you explicitly tell React to refresh specific cached data. This is where revalidation comes in.
Two Revalidation Functions
You've already seen these functions in earlier lessons, but here's when to use them in mutation workflows:
revalidatePath(path)
Invalidates all cached data associated with a specific route path. Use this after mutations that affect an entire page:
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title')
// Insert into database
await db.posts.create({ title })
// Refresh the posts list page
revalidatePath('/posts')
}
revalidateTag(tag)
Invalidates cached data marked with a specific tag. More granular than path-based revalidation:
'use server'
export async function updateUser(userId: string, data: FormData) {
await db.users.update(userId, data)
// Only refresh user-related caches
revalidateTag('user-profile')
}
The Pattern
- Perform the mutation (database write)
- Call
revalidatePathorrevalidateTag - React automatically refetches affected Server Components
- Users see updated data without full page reload
Think of it like telling React: "I changed something on the server—go refresh the pages that care about it."
Key Takeaway: Always call revalidatePath or revalidateTag after successful mutations in Server Actions to ensure users see fresh data without manual page refreshes.