What does the setState()
function run? Does it only run render()
?
What does the
setState()
function run? Does it only runrender()
No setState not only calls the render()
function but after setState
, the following lifecycle functions will run in order depending on what shouldComponentUpdate
returns
if shouldComponentUpdate
returns true(which is true by default).
1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate
if shouldComponentUpdate
returns false(if you have a custom implementation)
1. shouldComponentUpdate
One more thing to know about setState is that, it only triggers the re-render for the current component and all its children(considering no implementation of shouldComponentUpdate
for any of its children), Its doesn't trigger a re-render of the parent component and hence the reconcilation
doesn't happen for the parent components but only for itself and its children.
A DEMO of what happens when setState
is called.
class App extends React.Component {
state = {
count: 0
}
componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps parent');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate parent');
return true;
}
componentWillUpdate() {
console.log('componentWillUpdate parent');
}
render() {
console.log('render parent')
return (
)
}
componentDidUpdate() {
console.log('componentDidUpdate parent')
}
}
class Child extends React.Component {
componentWillMount() {
console.log('componentWillMount child');
}
componentDidMount() {
console.log('componentDidMount child');
}
componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps child');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate child');
return true;
}
componentWillUpdate() {
console.log('componentWillUpdate child');
}
render() {
console.log('child')
return (
{this.props.count}
)
}
componentDidUpdate() {
console.log('componentDidUpdate child')
}
}
ReactDOM.render( , document.getElementById('app'));
To add an explanation for the question that @poepje added on your question
What setState does?
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
React has a very good documentation on this function here
You could also see the following answer on how setState works:
setState doesn't update the state immediately