In my Next.js app, I have two pages, where each page sets a random person name when the component is loaded for the first time.
simpsons.tsx
export default function Simpsons() {
const [person, setPerson] = useState<string>();
useEffect(() => {
const persons = ["Homer", "Marge", "Lisa", "Bart", "Maggie"];
const random = Math.floor(Math.random() * persons.length);
setPerson(persons[random]);
}, []);
return (
<div>
<h1>{person} simpson</h1>
</div>
);
}
friends.tsx
export default function Friends() {
const [person, setPerson] = useState<string>();
useEffect(() => {
const persons = ["Ross", "Monica", "Racheal", "Joey", "Phebee","Chandler"];
const random = Math.floor(Math.random() * persons.length);
setPerson(persons[random]);
}, []);
return (
<div>
<h1>My friend {person}</h1>
</div>
);
}
My _app.tsx file is wrapped with a layout component and I switch the pages using the navbar in the layout component. When I go to the friends' page and then come back to the Simpsons page, previously selected Simpson should be there. (COMPONENT SHOULD NOT RE-RENDER EVERY TIME I SWITCH THE PAGES)
For this simple use case, we can use the state management solution like context. But my goal is not to keep state, persist. My goal is to prevent the re-renderings.
How can I achieve this using Next.js?
Navigating from one page to another causes the first page component to un-mount and second page to mount. Navigating back to first page using next router does the same thing.
useEffect(() => {
const persons = ["Homer", "Marge", "Lisa", "Bart", "Maggie"];
const random = Math.floor(Math.random() * persons.length);
setPerson(persons[random]);
}, []);
Ideally to handle such scenarios, it is best advised to decouple this logic from page mount/unmount function.