Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active November 17, 2023 17:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragland/94711efab9c4f21ef5fb9914b0f25892 to your computer and use it in GitHub Desktop.
Save gragland/94711efab9c4f21ef5fb9914b0f25892 to your computer and use it in GitHub Desktop.
Next.js routing to dynamic path without hitting server
'use client'
// ⛔️ DISCLAIMER: This is most likely premature optimization and adds code complexity.
// Only use if you really need to shave off that extra 100-200ms.
function MyComponent({ data }){
return (
<a
href={`/item/${data.id}`}
onClick={(e) => {
// Store item data in client cache
storeInCache("item", data);
// Take user to /item, not /item/[id]
e.preventDefault();
router.push("/item");
}}
>
Let's goooo
</a>
);
}
// app/item/page.js
function ItemStaticPage() {
// Get item data from client cache
const data = getFromCache("item");
// Immediately update URL to /item/:id
// replaceState is now supported by Next with the windowHistorySupport experimental flag
// See https://github.com/vercel/next.js/pull/58335
useEffect(() => {
window.history.replaceState(null, '', `/item/${data.id}`)
}, [data.id]);
// Render UI with data
return <ItemUI item={data} />
}
// app/item/[id]/page.js
// If user does a hard refresh it would load this page instead
async function ItemPage({ params }) {
// Get item data from client cache
const data = await getItemFromDB(params.id)
// Render UI with data
return <ItemUI item={data} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment