Refreshing the Page
Part of the Next.js Essentials section of Coddy's React journey — lesson 32 of 47.
You've been living with a lie for two lessons. Submit the form, and the item really is saved, but the screen doesn't move. Reload the page and there it is.
The reason is exactly what makes Server Components fast. The page read its data once, on the server, and what the browser holds is the finished result. Your action changed the data behind it. Nobody told the page.
The fix is one line, at the end of the action:
'use server';
import { revalidatePath } from 'next/cache';
import { saveTask } from '../lib/db';
export async function addTask(formData) {
saveTask(formData.get('title'));
revalidatePath('/');
}revalidatePath('/') throws away what Next.js has cached for that route and renders it again (on the server, with fresh data), then swaps the new result into the page. No reload, no spinner, no state.
The argument is the route to re-render, written the way it appears in the URL: '/' for the home page, '/tasks' for a tasks page. Point it at the wrong path and nothing visible happens: the classic "my action works but the list is stale" bug.
Sometimes you don't want to stay put at all. For "save it, then go somewhere", a Server Action can finish with redirect():
import { redirect } from 'next/navigation';
export async function createPost(formData) {
const id = savePost(formData.get('title'));
redirect(`/posts/${id}`);
}Same import you'd use in a page. Reach for revalidatePath when the user stays on the page, and redirect when they move on.
Challenge
EasyaddTask saves correctly, but the list on screen never updates. Fix it.
- In
app/actions.js, importrevalidatePathfrom'next/cache'. - Call it with the home route,
'/', after the task is saved.
Nothing in app/page.jsx needs to change: this is a one-import, one-line fix.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing3Layouts & Metadata
The Root LayoutShared NavigationNested LayoutsPage MetadataDynamic MetadataRecap: Layouts6Server Actions
What Is a Server ActionForms That ActReading Form DataRefreshing the PageRecap: Server Actions