• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

45
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 1 month 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 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.