React.js memo function in functional component

React JSJavascript LibraryFront End Technology

We have shouldComponentUpdate in class based component as lifecycle method. This method can be used to achieve the performance optimization by comparing props (previous and next) and executing render conditionally .

We have React.PureComponent as well which can do shallow comparison of state and props. But in functional component we don’t have such methods.

Now, React has provided a memo method which will do the same functionality for the functional components.

const functionalComponent = React.memo(function functionalComponent(props) {
   /* render using props */
});

We have wrapped the component inside the memo method. Memo method will memorize the result till the props are same. Once props are changed it will re-render the function. This is the default behavior with memo but we can also give our own custom method for comparing the props based on our requirement.

functionfunctionalComponent(props){
   /* render using props */
}
functionareEqual(prevProps, nextProps){
   /*
   return true if preProps and nextProps are equal else false
   */
}
exportdefault React.memo(functionalComponent, areEqual);

Note that the memo method only does shallow comparison of props and in-depth comparison if props contains nested data structures. If we need in-depth comparison we can do it by adding custom comparison function for it in memo function.

The second argument passed to the memo method decides when to re-render the function. Inside the are Equal we can add the custom logic for props comparison.

This is purely added for performance optimization and should not be used for preventing the render method.

React.memo is implemented as higher order component.

raja
Published on 04-Sep-2019 11:07:57
Advertisements