What is memo in react?

Viewed 4735

I am learning latest react features. As per docks memo works like shouldComponentUpdate or PureComponent in functional component but how do I use this memo concept in functional component.

Say I have below component using class

import React, { Component } from 'react';
class Test extends Component {
   shouldComponentUpdate(nextProps, nextState) {
     return this.props.text != nextProps.text;
   }
   render(){
     const { text } = this.props;
     return(
       <div>
          <h1>{text}</h1>
       </div>
     )
   }
}

Functional component

function Test = props => {
  const { text } = props;
     return(
       <div>
          <h1>{text}</h1>
       </div>
     )
}

How can I write class component using memo in functional component

2 Answers

Memo works as a higher order component, and you can simply just wrap your functional component export with it. Every time your application updates, memo will automatically perform a shallow comparison of props to determine if they've changed, and if the component needs to re-render.

export default React.memo(Test);

React.memo() is a HOC that takes a functional component and returns a component that behaves the same as a PureComponent.

const MyComponent = React.memo(function MyComponent(props) {
  /* only rerenders if props change */
});

Update: React.memo also accepts a compare function as second argument. By using this function, we can compare props not in a shallow way but whichever way we want to. This gives more control over preventing update of component. Use this function when your props contain complex Objects and you want to compare fields of these Objects while determining if your component should update. E.g.

const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
}, (props1, props2) => {
prop1.my_property_to_check === prop2.my_property_to_check
});
Related