In React, every time a component is rendered/re-rendered, it regenerates all of it's child nodes/components using createElement
. How does React know when to persist the components state between re-renders?
As an example, consider the following code:
class Timer extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(state => ({ seconds: state.seconds + 1 }));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return createElement('div', null,
'Seconds: ',
this.state.seconds
);
}
}
class Button extends Component {
constructor(props) {
super(props);
this.state = { clicks: 0 };
}
click() {
this.setState(state => ({ clicks: state.clicks + 1 }));
}
render() {
return createElement('button', { onClick: () => this.click() },
createElement(Timer, null),
'Clicks: ',
this.state.clicks
);
}
}
render(createElement(Button, null), document.getElementById('root'));
You can try this code with the Preact REPL here.
Notice that when the button is pressed and the clicks value is updated, the state of the Timer
component persists and is not replaced. How does React know to re-use the component instance?
While this may seem like a simple question at first, it becomes more complex when you consider stuff like changing the props passed to a child component or lists of child components. How does React handle changing the props of a child component? Does the child component's state persist even though it's props have changed? (In Vue, the state of a component does persist when it's props change) How about lists? What happens when an entry in the middle of a list of child components is removed? A change to a list like that would obviously generate very different VDOM nodes, yet the state of the components still persists.
createElement
does not create a new component. It returns a description (aReactElement
) which component to render in that place, with what properties and children. This is what react uses to determine whether the component tree changed.