Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance on PureComponent vs stateless functional component

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.

like image 518
CaribouCode Avatar asked Mar 18 '18 22:03

CaribouCode


2 Answers

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.

like image 102
Dom Avatar answered Nov 13 '22 07:11

Dom


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 });
  }
}
like image 30
Andrew Miroshnichenko Avatar answered Nov 13 '22 05:11

Andrew Miroshnichenko