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

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

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