https://javascript.plainenglish.io/react-memo-a-higher-order-component-7bcb392ac40e
Image created by the author on Canva
A higher-order component (HOC) is an advanced technique in React for reusing component logic, as mentioned in the React Docs. A HOC is not a part of the React API, but it is just a function with a component as an argument and returns a new component.
As mentioned in the title, React.memo is a higher-order function. It is used to memoize the result of our component, which helps to boost the performance of our React application.
In simple terms, if our component returns the same result for the same prop values passed to it, then rendering the same result ruins the performance of the application. A React memo is the solution to this problem. We just need to wrap our component in a call to React.memo, so React will skip rendering the component, and reuse the previous rendered result.
Now, let’s consider a simple example to clear the concept more precisely. Assume we have a parent component and a child component. Now, whenever the parent component re-renders due to its own state changes, a child component will also re-render, which is a common nature of React. Here, there are no state changes happening in the child component, which means the unnecessary rendering of a child component will affect the performance. To solve this problem we just need to wrap our child component in a React.memo, so React will use the previous rendered result.
See the example below. In our example, we have a parent component that prints value1, and a child component that prints value2 on browser display.
In the first case without using Memo, the child component re-renders on changes in both values, which is called poor performance because the child component only uses value2 as its prop.
Our second case using Memo is the solution to this problem. In that case, I have wrapped the child component in the React Memo, so it will only re-render when value2 will be changed.
Output video created by the author
Output video created by the author