Search code examples
javascriptreactjsreact-hooksrenderingreact-component

react - Different random value between parent and child component


I face this issue in my real project. To present it more clearly, I built a very basic project, which consists of just a parent and a child component.

I have a random value that I define (no matter if as a state variable or as a 'regular' variable) in the body of the parent component and pass it as props to the child component.
For some reason, when I log (console.log) this random value in the body of the parent component, it appears to be different from the value in the body of the child component. They are equal in the jsx of each component, and when I log the value in an useEffect hook in the parent, but different when I log them in the body of each component.

Parent component:

import React, { useEffect } from 'react';
import ChildComponent from './ChildComponent';

function App() {
  const rand = Math.random();
  console.log('parent - in body', rand);

  useEffect(() => {
    console.log('parent - in useEffect', rand);    
  });

  return (
    <div>
      <h1>parent {rand}</h1>
      <ChildComponent rand={rand}></ChildComponent>
    </div>
  );
}

export default App;

Child component:

import React from 'react';

function ChildComponent(props) {
  console.log('child', props.rand);
  return (
    <div>
      <h3>child {props.rand}</h3>
    </div>
  );
}

export default ChildComponent;

The results (the different value in the console is circled):

enter image description here

Can someone explain this behavior?


UPDATE:
I realized that the <React.StrictMode> in the index.js file was responsible for the re-rendering, hence the different values of the random variable.
However:

  • If due to the strict mode the component was rendered twice, why there is only one appearance for each console.log()?
  • Is it safe to remove the strict mode to solve this issue (I don't want to lose necessary things on the other hand)?
  • Which component was rendered twice (the parent, the child, or both), and how does it works?

Solution

  • This is probably a problem caused for a re-render.

    The first value logged is the first generated value, after a re-render appears the new value and this is logged for the useEffect, because useEffect executes after the component is mounted and the DOM is loaded.

    Moreover, the re-render is probably cause for the <StrictMode> in your index.js, this produce an intentional re-render, to test side-effects and search for problems.