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
State is not updated in StrictMode

After some trial I discovered following problem occurs in strict mode. I would be interested if someone can explain why.

Take this simple example where inside render I am just scheduling a timeout which updates state:

Example:

let firstRender = true; // Normally I would use ref but I was playing with example

export default function App() {
  let [data, setData] = React.useState({ name: 'Nick' });

  // Schedule a timeout on first render
  if (firstRender) {
    setTimeout(() => {
      console.log('Running');

      setData((ps) => ({
        ...ps,
        name: 'Paul',
      }));
    }, 1000);
  }

  console.log('Running render');
  firstRender = false;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

If you run this example without Strict mode, then you will see "Paul" on screen after one second, as I was expecting.

If you use Strict mode, it will always show "Nick" on screen. Idea why?

UPDATE: it seems using useRef instead of the global variable firstRender fixes this problem also in Strict mode. Curious why that's the case?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is due to the fact that strict mode intentionally invokes your function component body twice (when in dev mode) to help spot unintended side effects.

On the second invocation, your firstRender variable is false so your setTimeout doesn't run.

Important to note that this second invocation isn't just a re-render like you'd get from a state update. It's a second invocation of the entire component body. State is not preserved. React invokes your component function once, discards the result, and invokes it a second time to get the output.

From the docs:

Because the above methods might be called more than once, it’s important that they do not contain side-effects.

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Function component bodies
about 4 years ago · Juan Pablo Isaza Relatório

0

Q. it seems using useRef instead of the global variable firstRender fixes this problem also in Strict mode. Curious why that's the case?

According to React Docs,

Ref is also useful to keep some mutable value around. The value stores in ref, will not change during subsequent re-renders, unless explicitly changed.

Therefore, for values you don't want to change (maybe some expensive calculation) or for other reasons, use useRef.

The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

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