Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!