How do server actions automatically update the user interface after making a change to data?
Short answer
After a server action completes its update, you typically call revalidatePath or revalidateTag inside it to clear the relevant cached data, which causes Next.js to refetch and re-render the affected parts of the page with the newly updated data the next time they are displayed.
Advertisement
AModel answer
After a server action completes its update, you typically call revalidatePath or revalidateTag inside it to clear the relevant cached data, which causes Next.js to refetch and re-render the affected parts of the page with the newly updated data the next time they are displayed.
'use server';
import { revalidatePath } from 'next/cache';
export async function markComplete(todoId) {
await db.todo.update({ where: { id: todoId }, data: { completed: true } });
revalidatePath('/todos');
}Real-world example
A todo list automatically shows a task as completed right after a user checks it off, thanks to the server action revalidating the todos page immediately after updating the database.
Likely follow-ups
- What happens if you forget to call revalidatePath after a data mutation?
- Can a single server action revalidate multiple different pages?
Related topics