Consider the following React code:
class Todos extends React.Component {
constructor(props) {
super(props);
this.state = { item: 'Test', };
}
render() {
return <TodoItem item={this.state.item} />
}
}
class TodoItem extends React.PureComponent {
render() {
return <div>{this.props.item}</div>
}
}
function TodoItem(props) {
return <div>{props.item}</div>
}
Above there is a stateful parent component Todos
and 2 versions of the same child component TodoItem
. One of the versions is a pure component and the other is a stateless functional component.
I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component?
If not then why? It seems that by using either I am telling React my component has no state and therefore will only update if the parent component's state changes.
I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component?
No, not yet. There were indications from the React team this will change in the future, but as of today, stateless functional components still behave like React.Component in regards to rerendering.
If you need to optimize for performance, stick with React.PureComponent
or React.Component
implementing shouldComponentUpdate
. Keep in mind that if you're using redux and react-redux, connect()
will try to handle the shallow compares for you as well on both functional and class-based components (read up on in in the docs). You might also want to check out recompose and its onlyUpdateForKeys
helper, for example.
It really depends on how you call your pure component in JSX. When using mounting (as in your snippet) it don't get you a lot of optimization. @Dominik and folks in comments to question describe why. But here guy states that calling pure components as functions can result in 45% speed up.
Todos
component will look like this:
class Todos extends React.Component {
constructor(props) {
super(props);
this.state = { item: 'Test', };
}
render() {
return TodoItem({ item: this.state.item });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With