Skip to content

Instantly share code, notes, and snippets.

@imjacobclark
Created November 2, 2025 21:39
Show Gist options
  • Select an option

  • Save imjacobclark/0833517fcce0bd05e1549efcb3131c00 to your computer and use it in GitHub Desktop.

Select an option

Save imjacobclark/0833517fcce0bd05e1549efcb3131c00 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
const PageOne = () => <h1>Page One</h1>
const PageTwo = () => <h1>Page Two</h1>
export default function Home() {
const [page, setPage] = useState(-1);
const pages = [PageOne, PageTwo];
const Page = pages[page];
useEffect(() => {
const currentHistoryState = window.history.state ?? {};
const onPopState = (event) => {
setPage(event.state?.location);
};
const newHistoryState = {
...currentHistoryState,
location: -1
}
window.history.pushState(newHistoryState, '', '/');
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, [])
return (
<main>
{page === -1 && <h1>Hello Next.js</h1>}
{page !== -1 && pages[page] && <Page />}
{page >= pages.length && <h1>The end.</h1>}
<button
onClick={() => {
const next = page + 1;
setPage(next);
window.history.pushState(
{ ...(window.history.state ?? {}), location: next },
'',
'/'
);
}}
>
Next Page
</button>
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment