Home > Net >  React.memo vs React.PureComponent for function components
React.memo vs React.PureComponent for function components

Time:12-16

Right now my app uses functional components exclusively.

I was wondering, if I have a component that should really be a pure component. To get a bit more performance, should I

  • I rewrite my code to a class component that extends React.PureComponent
  • Use React.memo HoC to wrap my existing functional component?
  • Use Recompose.pure HoC to wrap my existing functional component?
  • or just leave it alone since function components are pure already (not sure if this statement is correct)

This isn't premature optimization, the code is obviously pure, I am just wondering what is the recommended correct way to do it. This isn't really an opinion based thing because there should only be one way to make function components pure.

I'm leaning towards converting to a React.PureComponent, since I am presuming React.memo will use memory regardless where as the PureComponent would have different optimizations.

References:

CodePudding user response:

TL;DR: memo

Per the documentation of PureComponents

We recommend to define components as functions instead of classes. See how to migrate.

They have this example

class Greeting extends PureComponent {
  render() {
    console.log("Greeting was rendered at", new Date().toLocaleTimeString());
    return <h3>Hello{this.props.name && ', '}{this.props.name}!</h3>;
  }
}

should be

const Greeting = memo(function Greeting({ name }) {
  console.log("Greeting was rendered at", new Date().toLocaleTimeString());
  return <h3>Hello{name && ', '}{name}!</h3>;
});

They also added this note as a bonus

Unlike PureComponent, memo does not compare the new and the old state. In function components, calling the set function with the same state already prevents re-renders by default, even without memo.

  • Related