Home > Enterprise >  ReactJS 17.0.2 seems to call function again when putting value into DOM
ReactJS 17.0.2 seems to call function again when putting value into DOM

Time:05-06

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.

CodePudding user response:

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

  • Related