FreeCodeCamp states that if any component receives new
state
or newprops
, it re-renders itself and all its children. This is usually okay. But React provides a lifecycle method you can call when child components receive newstate
orprops
, and declare specifically if the components should update or not. The method isshouldComponentUpdate()
, and it takesnextProps
andnextState
as parameters.You can use
shouldComponentUpdate()
to prevent this by comparing the props. The method must return a boolean value that tells React whether or not to update the component.Code:
class OnlyEvens extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState) {
console.log('Should I update?');
// Change code below this line
return true;
// Change code above this line
}
componentDidUpdate() {
console.log('Component re-rendered.');
}
render() {
return <h1>{this.props.value}</h1>;
}
}
class Controller extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
this.addValue = this.addValue.bind(this);
}
addValue() {
this.setState(state => ({
value: state.value + 1
}));
}
render() {
return (
<div>
<button onClick={this.addValue}>Add</button>
<OnlyEvens value={this.state.value} />
</div>
);
}
}
- Answer:
class OnlyEvens extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState) {
console.log('Should I update?');
// Change code below this line
if (nextProps.value % 2 === 0) {
return true
} else {
return false;
}
// Change code above this line
}
- You click the
Add
button and watch the order of events in your browser's console as the lifecycle hooks are triggered.
Top comments (1)
Nice write up! Something else to consider is extending
React.PureComponent
in place ofReact.Component
if your optimization is a shallow check of props and state, and you get theshouldComponentUpdate
for free!Check out the docs here: reactjs.org/docs/react-api.html#re...