React Pure Component and memo



React.PureComponent

 

React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

 

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

 

Note

 

React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data.

 

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

 

React.memo

 

const MyComponent = React.memo(function MyComponent(props) {

  /* render using props */

});

React.memo is a higher order component. It’s similar to React.PureComponent but for function components instead of classes.

 

If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

 

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

 

function MyComponent(props) {

  /* render using props */

}

 

function areEqual(prevProps, nextProps) {

  /*

  return true if passing nextProps to render would return

  the same result as passing prevProps to render,

  otherwise return false

  */

}

 

export default React.memo(MyComponent, areEqual);

 

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

 

Note

 

Unlike the shouldComponentUpdate() method on class components, the areEqual function returns true if the props are equal and false if the props are not equal. This is the inverse from shouldComponentUpdate.

Comments

Popular posts from this blog

Set Up Babel and Webpack

Typescript Setup

Typescript + React Setup