A <RefreshOnFocus />
component that can be dropped into any React Server Component in a Next.js app, causing it to refresh whenever the browser window is focused.
The cards on this page use a key
with their dynamic data to run a CSS animation whenever their data changes.
Code
// refresh-on-focus.tsx
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export function RefreshOnFocus() {
const { refresh } = useRouter();
useEffect(() => {
const onFocus = () => {
refresh();
};
window.addEventListener("focus", onFocus);
return () => {
window.removeEventListener("focus", onFocus);
};
}, [refresh]);
return null;
}
Usage
// src/app/page.tsx
import { RefreshOnFocus } from "./refresh-on-focus";
export default function Home() {
let date = new Date();
return (
<div>
<p>This component was rendered at {date.toString()}</p>
<RefreshOnFocus />
</div>
);
}