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

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

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 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