Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda