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

193
Vistas
ReactJS 17.0.2 seems to call function again when putting value into DOM

There is a strange behavior when running ReactJS 17.0.2.

I have a function that generates a random number outside of a component. I assign the return value of this function to a constant inside the component and afterwards console.log it and display in the DOM. Strangely the two are different. This effect is not happening in ReactJS 18.0 and above but I still want to understand what is happening here.

const randomNum = () => {
    return 0.5 - Math.random() * 100;
};

export default function App() {
   const randN = randomNum();
   console.log(randN);
   return (
       <div className="App">
           <p>Random number is: {randN}</p>
       </div>
  );
}

I would expect the console.log and the DOM to show the exact same values, but that is not the case.

Here is a sandbox that shows this behavior.

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

0

<StrictMode> deliberately renders the component twice, and the version of react you're using also secretly overwrites console.log during the second render to silence the second log. So you're seeing the log from the first render, and the value from the second render.

To see the second log statement, which will match with what's on the dom, you can do this:

import "./styles.css";

const randomNum = () => {
  return 0.5 - Math.random() * 100;
};

const log = console.log;

export default function App() {
  const randN = randomNum();
  log(randN);
  return (
    <div className="App">
      <p>Random number is: {randN}</p>
    </div>
  );
}

Later versions of react no longer mess with console.log, since it was causing confusions like yours.

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