Reputation: 646
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.
Upvotes: 6
Views: 3126
Reputation: 2255
createElement
vs render
vs mountWhen a React Component such as your Button
is rendered, a number of children are created with createElement
. createElement(Timer, props, children)
does not create an instance of the Timer
component, or even render it, it only creates a "React element" which represents the fact that the component should be rendered.
When your Button
is rendered, react will reconcile the result with the previous result, to decide what needs to be done with each child element:
Button
is rendered for the first time, all of the children will be new (because there is no previous result to match against).An element "matches" another one if React compares them and they have the same type.
The default way for React to compare children, is to simply iterate over both lists of children at the same time, comparing the first elements with each other, then the second, etc.
If the children have key
s, then each child in the new list is compared to the child in the old list that has the same key.
See the React Reconciliation Docs for a more detailed explanation.
Your Button
always returns exactly one element: a button
. So, when your Button
re-renders, the button
matches, and its DOM element is re-used, then the children of the button
are compared.
The first child is always a Timer
, so the type matches and the component instance is reused. The Timer
props did not change, so React might re-render it (calling render
on the instance with the same state), or it might not re-render it, leaving that part of the tree untouched. Both of these cases would result in the same result in your case - because you have no side-effects in render
- and React deliberately leaves the decision of when to re-render as an implementation detail.
The second child is always the string "Clicks: "
so react leaves that DOM element alone too.
If this.state.click
has changed since the last render, then the third child will be a different string, maybe changing from "0"
to "1"
, so the text node will be replaced in the DOM.
If Button
s render
were to return a root element of a different type like so:
render() {
return createElement(this.state.clicks % 2 ? 'button' : 'a', { onClick: () => this.click() },
createElement(Timer, null),
'Clicks: ',
this.state.clicks
);
}
then in the first step, the a
would be compared to the button
and because they are different types, the old element and all of its children would be removed from the DOM, unmounted, and destroyed. Then the new element would be created with no previous render result, and so a new Timer
instance would be created with fresh state, and the timer would be back at 0.
Timer matches? |
previous tree | new tree |
---|---|---|
no match | <div><Timer /></div> |
<span><Timer /></span> |
match | <div>a <Timer /> a</div> |
<div>b <Timer /> b</div> |
no match | <div><Timer /></div> |
<div>first <Timer /></div> |
match | <div>{false}<Timer /></div> |
<div>first <Timer /></div> |
match | <div><Timer key="t" /></div> |
<div>first <Timer key="t" /></div> |
Upvotes: 5
Reputation: 13588
Never used Vue, but this is my take.
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)
This depends on how you handle the props in your child.
This child will re-render every time you change (mutate) your props.
const Child = (props) => {
return <div>{ props.username }</div>;
};
This child will not re-render when props change since the return value is dependent on the local state, and not the props.
const Child = (props) => {
const [state, setState] = useState(props.username);
return <div>{ state }</div>;
};
This child will re-render when props change, as local state updates with the new props.
const Child = (props) => {
const [state, setState] = useState(props.username);
useEffect(() => {
// changing props changes the component's state, causing a re-render
setState(props.username);
}, [props]);
return <div>{ state }</div>;
};
As seen in the examples above, the programmer is the one in control of whether React triggers a re-render of a child.
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.
When a list of children is involved (eg. when .map
is used) React will require the key parameter, so that React will be aware what was add/removed/changed between parent component re-renders.
React requires that the same key be used for the same components to prevent unnecessary re-renders (don't use Math.random()
as your key).
Upvotes: 1