The next phase in the lifecycle is when a component is updated. This occurs whenever there is a change in the component’s state or props. During an update, React calls five built-in methods in this order:
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
The render() method is required and will always be called, while the others are optional and will be called if defined.
getDerivedStateFromProps
During updates, the getDerivedStateFromProps()
method is also called. It’s the first method triggered when a component updates and remains the appropriate place to adjust the state
object based on the initial props.
In the example below, pressing the button changes the favorite color to blue, but since getDerivedStateFromProps()
updates the state with the color from the favcol
attribute, the favorite color is still rendered as yellow.
Example:
When a component is updated, the getDerivedStateFromProps() method is invoked.
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props .favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header favcol="yellow" />);
|
shouldComponentUpdate
In the shouldComponentUpdate() method, you can return a Boolean value to determine whether React should proceed with rendering. By default, it returns true. The example below demonstrates what happens when shouldComponentUpdate() returns false.
Example:
Stop the component from rendering at any update:
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header />);
|
Example:
The same example as above, but this time the shouldComponentUpdate()
method returns true
.
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1>
<button type="button" onClick={this.changeColor}>Change color</button> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header />);
|