Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda