1

I have a question about PureComponent in react. As you know, it is really useful in long FlatLists, to avoid unnecessary re-renders. But, what happen if I wrap a PureComponent in a HOC like this:

const CachedImage = withCache(
  class CachedImage extends React.PureComponent {
    render() {
      console.log("Rendering");
      return <Image {...this.props} />;
    }
  }
);

... and use it as FlatList item. I mean, will CachedImage avoid unnecessary re-renders too? I don't know it as it seems that is a child the one which extends PureComponent and not the final component itself...

Thank you.

Pd: withCache HOC is implemented as normally every HOC is:

  const withCache = (Component) => {
      const Wrapped = (props) => {
           ...
Raul
  • 2,673
  • 1
  • 15
  • 52

1 Answers1

1

Only difference between Component and PureComponent is that PureComponent doesn't implement shouldComponentUpdate(), but PureComponent implements it with a shallow prop and state comparison.

That means that it does a simple shallow comparison of your props which is much faster but requires simple objects to be passed as props in order for it to work correctly. So it's not just about extending PureComponent that gives you unnecessary re-renders, but you have to think whether your props to that component will be compared correctly.

You can read more about PureComponent here and here is some info on how shallow compare works actually.

zhuber
  • 5,364
  • 3
  • 30
  • 63