Skip to content

Question from react reconciliation #11651

@ghost

Description

With the goal to better understand react reconciliation I created this example

// Just a simple timer component basically which shows each second passed
class Stateful extends React.Component{
 constructor(props){
   super(props)
     this.state={timer:0}
   }
    
  componentDidMount(){
    let that = this;
    setInterval(function(){
    that.setState(function(prevState){return {timer: prevState.timer+1}})
    }, 1000);
  }
  render(){
    return <p>{this.state.timer}</p>
  }
}

// Just a demo class for understanding reconciliation
class Demo extends React.Component {
   constructor(props){
     super(props)
     this.state={}
   }
  componentDidMount(){
    let that = this;
    setTimeout(function(){
    that.setState({showWarning: true})
  }, 3000);
  }
  render() {
    if (this.state.showWarning) {
      return (
        <div>
          <Stateful /> // I was hoping this would create a new instance of Stateful Component after 3 seconds
        </div>
    );
  }

    return (
      <div>
        <Stateful />
      </div>
    );
}
}

ReactDOM.render(
  <Demo />,
  document.getElementById('container')
);


You can see after three seconds showWarning is set to true. So I was believing that after three seconds I would get a new instance of <Stateful> component (because it lives in a different div than the one rendered already) - hence I would see the output of Stateful component starting from 0 again, but the timer just continued to increase on the screen.... So the output basically is:
0...1...2...3...4....(and so on each second).
Whereas I expected it to show 0...1..2.. and on third second do a restart basically and start 0...1...2...3...etc.
What did I miss from reconciliation docs that led me believe in this? (I have a feeling the react docs on this misses to highlight this, or it might be I missed something?)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions