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

86
Vistas
Prevent loading components with default values in React useState

I am working with offset pagination in typescript react.

I have two states that contain pageNumber and offset. The default page is set to 1 and the default offset is set to 0 as you can see below.

useState Hook

  const [currentPage, setCurrentPage] = useState(1);
  const [calculatedOffset, setCalculatedOffset] = useState(0);

On load, the component fetches pageNumber and calculatedOffset from the localStorage and updates the defaults of the useState values.

useEffect Hook

  useEffect(() => {
    if (typeof window !== "undefined") {
      const integerPage = parseInt(localStorage.getItem("currentPage") || "1");
      setCurrentPage(integerPage);

      const integerOffset = parseInt(localStorage.getItem("calculatedOffset") || "0");
      setCalculatedOffset(integerOffset);
    }
  }, []);

THE PROBLEM:

The problem I am facing is that whenever the component loads, it loads up with the values of the default state, i.e. pageNumber: 1, calculatedOffset: 0 for half a second then changes it to the updated state that was which was updated when the useEffect hook ran. So on every load, the component flashes the data of the default state before ending up from the updated state fetched from localStorage.

Is there a way I can make it where the component only loads when the states have ended up on their final values and prevent the old states flashing for half a second behaviour every time the component loads?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

useEffect runs when the component has been rendered fully. So before that happens, useState is already used to initialise the variables according to which your components are initially rendered.

To prevent the initial render according to the initialised value from useState, set both to null in useState and in the component, render the elements conditionally:

{!currentPage || element}

or

{currentPage && element}
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