Defining Pure Components
- They are created by extending the
PureComponentclass - A PureComponent implements the
shouldComponentUpdatelifecycle method - A shallow comparison is performed on props/state of components
- If there isn't a difference, the component isn't rerendered
- Implying, a pure component is used for performance boosts
- Children components may be pure components to avoid unexpected behavior
- The state shouldn't be mutated for pure components
- A new object should be returned that reflects the new state
Illustrating a Parent Component
class ParentComp extends Component {
constructor(props) {
super(props)
this.state = {
name: 'Mike'
}
}
componentDidMount() {
setInterval(() => {
this.setState({
name: 'Mike'
})
}, 2000)
}
render() {
console.log('Parent Comp render');
return (
<div>
<RegComp name={this.state.name} />
<PureComp name={this.state.name} />
</div>
)
}
}Illustrating a Regular Component
class RegComp extends Component {
render() {
console.log('Regular Comp render')
return (
<div>
Regular Component {this.props.name}
</div>
)
}
}Illustrating a Pure Component
class PureComp extends PureComponent {
render() {
console.log('Pure Comp render')
return (
<div>
Pure Component {this.props.name}
</div>
)
}
}Illustrating the Difference
- A regular component doesn't implement the
shouldComponentUpdatemethod - For a regular component, it always returns true by default
- A pure component implements the
shouldComponentUpdatemethod with a shallow props and state comparison - For example, a shallow comparison will always return true if the strings are the same values
- However, two objects return false if they don't have the same identity
Parent Comp render
Reg Comp render
Pure Comp render
Parent Comp render
Reg Comp render
Parent Comp render
Reg Comp render
...References
Previous
Next