Mounting
Component added to DOM
Method
- componentDidMount(): doing initialization work that require DOM
- e.g. add listener, fetch data from server
Updating
setState() is called or prop updated
Method
- getSnapshotBeforeUpdate(): doing saving work
- takes snapshot of current prop & state
- componentDidUpdate(previousProps, previousState, snapshot): get current prop & state before updated
- shouldComponentUpdate(newProps, newState): optimize update
- e.g. compare with the current state and decide not to update the component
Unmounting
Component removed from DOM
Method
- componentWillUnmount(): doing cleanup work
- e.g. close stuff to prevent memory leak
Example
class TextAreaCounter extends React.Component {
// ...
componentDidMount() {
console.log('componentDidMount');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate ', prevProps, prevState, snapshot);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('getSnapshotBeforeUpdate', prevProps, prevState);
return 'hello';
}
shouldComponentUpdate(newProps, newState) {
console.log('shouldComponentUpdate ', newProps, newState);
return true;
}
// ...
}
Order of method calling:
- componentDidMount(): start
- shouldComponentUpdate(): update comes in
- getSnapshotBeforeUpdate(): update will happen
- componentDidUpdate(): update done
- componentWillUnmount(): end
Update Checking
- Implement incoming change checking logic in componentDidUpdate:
componentDidUpdate(prevProps, prevState) {
// checking logic
if(condition){
this.setState({ xxx: this.props.xxx});
} else{
this.setState({ xxx: prevState.xxx});
}
}
- You can always use prevState/prevProps to revert back the update
- If the update is valid, go ahead and set the value to this.props/this.state which is updated