We have a static page that shows the current date and time, but it would be good to have it update automatically.
Automatic Revalidation
Let's make it update every 5 seconds.
To do that, we export a revalidate
constant, setting its value to 5
:
// inside app/page.tsx
export const revalidate = 5
export default function Home() {
...
Now our page will be regenerated every 5 seconds if there is an incoming request.
You can test this in the browser by refreshing. You'll notice that the timestamp updates every 5 seconds.
You can see this in the console as well:
Manually Triggering Revalidation
What if we want to trigger a revalidation manually instead of on a timer?
First, disable the timed revalidation by commenting out the revalidate
constant.
Then we'll create a RevalidateHomeButton
client component in the app directory:
// inside app/RevalidateHomeButton.tsx
"use client";
import { Button } from "@/components/ui/button";
export default function RevalidateHomeButton({
onRevalidateHome,
}: {
onRevalidateHome: () => Promise<void>;
}) {
return (
<Button onClick={async () => await onRevalidateHome()} className="mt-4">
Revalidate Home
</Button>
);
}
The RevalidateHomeButton
component will accept a server action onRevalidateHome
as a prop that will be called when the button is clicked.
We can then import the RevalidateHomeButton
to the Home
component:
// inside app/page.tsx
import RevalidateHomeButton from "./RevalidateHomeButton";
Inside of the page.tsx
file, we'll create the async onRevalidateHome
function that will trigger the revalidation of the homepage. The "use server";
pragma is used to define it as a server action, and we use the revalidatePath()
function to revalidate the root path (/
):
export default function Home() {
async function onRevalidateHome() {
"use server";
revalidatePath("/");
}
console.log(`Rendering / ${new Date().toLocaleTimeString()}`);
return (
<main>
<div>{new Date().toLocaleTimeString()}</div>
<RevalidateHomeButton onRevalidateHome={onRevalidateHome} />
</main>
);
}
Now, if you go back to the browser and hit the "Revalidate Home" button, it will trigger a revalidation of the homepage.
Remember, server actions is that they return promises. This means you need to make sure we're using await
when calling onRevalidateHome
inside of the RevalidateHomeButton
component. Otherwise, the revalidation might not happen as expected.
Next, we'll talk about how this full-route caching approach affects API routes.