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

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

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 Denunciar

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