- Mounting
- Updating
- Unmounting
* is required, others will be called if defined
Mounting phase - putting elements into the DOM#
constructor(props)
- called when component is initiated
- set initial
state
getDerivedStateFromProps( props, state )
- set
state
based on the initialprops
- (updates
state
from initial before render) - returns state object
- set
- *
render()
componentDidMount()
- run statements that requires that the component is already placed in the DOM
Updating phase - when component is updated#
getDerivedStateFromProps( props, state )
shouldComponentUpdate()
- return a Boolean that specifies whether React should continue with the rendering or not default is true
- *
render()
getSnapshotBeforeUpdate( prevProps, prevState )
- gives access to the
props
andstate
before the update (i.e. even after the update, you can check what the values were before the update) requirescomponentDidUpdate()
method
- gives access to the
componentDidUpdate()
Unmounting - when a component is removed from the DOM#
componentWillUnmount()
- is called when a component is about to be unmounted
Example#
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = { color: "red" };
}
static getDerivedStateFromProps(props, state) {
return { color: props.color };
}
shouldComponentUpdate() {
return true;
}
componentDidMount() {
setTimeout(() => {
this.setState({ color: "blue" });
}, 2000);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
const div1 = document.getElementById("div1");
div1.textContent = `Before the update Header color was: ${prevState.color}`;
return null;
}
componentDidUpdate() {
const div2 = document.getElementById("div2");
div2.textContent = `The updated Header color is: ${this.state.color}`;
}
componentWillUnmount() {
alert("the component named Header is about to be unmounted");
}
handleClick = () => {
this.setState({ color: "cyan" });
};
render() {
return (
<div style={{ color: this.state.color }} onClick={this.handleClick}>
<h1 className="title">Header {this.state.color}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}