Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Nextjs Memorizing the pages to prevent re-rendring

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!