Patternite Logo

Optimizing React Components with React.memo

1

React.memo is a higher order components that remembers the "props" of the component it wraps. Re-render occurs only when props change.

Loading...

Problem

When a setState is called on a parent component (in our case MyForm), the entire component re-renders, including all of its children components. Although MyForm is a small example, imagine a big and complex parent component with many nested children. With no optimization, redundant re-renders is an obvious waste of compute resources that could slow down your app and ultimately affect user experience.

Solution: What is React.memo?

React.memo(MyComponent [, propsCompareFn])

React.memo is a higher order component (HOC). In general, it provides the component it consumes with the special ability to remember the props from its previous render. In the grand scheme of a complex parent component, child components using React.memo are optimized to only re-render when their next passed in props are different from its previous render.

In addition, React.memo has a second optional argument that is a function. This function allows you to specify which prop you want React.memo to remember and track for triggering re-renders. For example line #102 in the code above, we only want our InputField to re-render when its value prop changes.

Resources

Profile picture for jonparkdev

| edited

Patternite © 2021

Patternite Logo