Himanshu Sharma
Himanshu Sharma

Reputation: 581

Props have different value for randomly generated ones in parent (react.js)

Weird behavior in React.js. When I am passing some randomly generated value in props. It is giving a different output in console logs.

While I debug it is again going back to App.js (Parent) and check its value but consoles are just 2, not 4.

What I am missing in react lifecycle or something here?

// App.js
function App() {
  const rand = Math.random();
  console.log(rand);
  return (
    <div className="App">
      <Board rand={rand} />
    </div>
  );
}

export default App;
// Board.js
function Board({ rand }){
    console.log(rand);
    return(
        <div className="Board"></div>
    );
}
export default Board;

Here is the github repo: [email protected]:senseihimanshu/minesweeper.git

Please check App.js and Board.js for further clarification and verify in console of dev tools that both the array are not same... This is the problem.

Upvotes: 1

Views: 374

Answers (1)

sidhant manchanda
sidhant manchanda

Reputation: 554

React.StrictMode renders 2 times to detect side effects in development mode

React 17 swallows some console.logs during second render , this happens only when strict mode is enabled https://github.com/facebook/react/issues/20090#issuecomment-715926549

Code ref: https://github.com/facebook/react/blob/7cb9fd7ef822436aef13c8cbf648af1e21a5309a/packages/react-reconciler/src/ReactFiberClassComponent.old.js#L170

how to Solve https://github.com/facebook/react/issues/20090#issuecomment-715927125

The view will be consistent though, better use a useEffect and calculate the value once on render.

Upvotes: 3

Related Questions