TL DR: Can I trust the reconciliation algorithm not to recreate an instance of my component with state simply because the change in the Virtual DOM was too complicated to keep track of?
I believe that React.Component instances are created and destroyed at React runtime to fit the Virtual DOM form. As a programmer, I declaratively describe the Virtual DOM, and the life cycle of instances is controlled by the Reag itself. I understand that a special reconciliation algorithm tries to complicate the reuse of as many old instances as possible when the Virtual DOM changes its shape. In addition, I understand that if the only difference is in the details, then the old instance simply updates and updates its details using life cycle methods.
I also expect that for functional components that simply map props to the Virtual DOM, it makes no sense to talk about the life cycle, since it doesn't really matter if it is the same or not the same instance. In particular, you do not need to trust the matching algorithm to be very smart, since the component will look and behave the same regardless of whether it is the same instance with updated details or a new instance.
But can I, and should I trust the matching algorithm in the case of state components?
Let's say that I have a component that stores some data in its state and directly on its instance. Moreover, suppose that the constructor of this component initializes both of them:
constructor(props) {
super(props);
this.state = {
value: ''
};
this.length = 0;
}
, , , , -
onChange = (e) => {
this.setState({value: e.target.value}
this.length = e.target.value.length;
}
, , React framework? "", , , , - "", - .
, , reset, key . ?
: key , , - ( , )? : ?
: https://codesandbox.io/s/9rqrPJnLD. :
class Stateful extends React.Component{
state = { now: new Date()};
render(){
return <div>{this.state.now.toString()}</div>
}
}
, , , div, :
class App extends React.Component{
state = { div: true}
componentDidMount(){
setInterval(()=>{
this.setState(state => {
return {div: !state.div}
});
},2000)
}
render(){
return React.createElement(this.state.div ? 'div' : 'span',null,React.createElement(Stateful))
}
}
, , , , . . : , .