DEV Community

Cover image for Optimizing Component Performance in React
Ricardo Maia
Ricardo Maia

Posted on

Optimizing Component Performance in React

𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰 is a higher-order function (HOC) in React that helps optimize the performance of functional components by preventing unnecessary re-renders. It memorizes the result of the component's rendering and only re-renders it if the 𝐩𝐫𝐨𝐩𝐬 change. This is useful when a component's props or state don't change often.

𝐇𝐨𝐰 𝐑𝐞𝐚𝐜𝐭.𝐦𝐞𝐦𝐨 𝐖𝐨𝐫𝐤𝐬

When a functional component is wrapped in 𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰, React performs a shallow comparison between the previous and new props. If the props haven't changed, the component won't re-render, saving performance resources by avoiding redundant rendering.

𝐁𝐚𝐬𝐢𝐜 𝐒𝐲𝐧𝐭𝐚𝐱
Image description

𝐒𝐢𝐦𝐩𝐥𝐞 𝐄𝐱𝐚𝐦𝐩𝐥𝐞
Imagine we have a Counter component and a child component that displays a static message. We can use React.memo for the child component to avoid re-rendering it every time the counter state changes, as long as its props remain the same.

𝐖𝐢𝐭𝐡𝐨𝐮𝐭 𝐑𝐞𝐚𝐜𝐭.𝐦𝐞𝐦𝐨:

Image description

In this example, every time the counter state changes, 𝘚𝘵𝘢𝘵𝘪𝘤𝘔𝘦𝘴𝘴𝘢𝘨𝘦 will re-render, even though its content remains unchanged.

𝐖𝐢𝐭𝐡 𝐑𝐞𝐚𝐜𝐭.𝐦𝐞𝐦𝐨:

Image description

Now, with 𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰, the 𝘚𝘵𝘢𝘵𝘪𝘤𝘔𝘦𝘴𝘴𝘢𝘨𝘦 component will only render once, unless its props change. Even if the counter updates, the static component will not be re-rendered.

𝐑𝐞𝐚𝐜𝐭.𝐦𝐞𝐦𝐨 𝐰𝐢𝐭𝐡 𝐂𝐮𝐬𝐭𝐨𝐦 𝐂𝐨𝐦𝐩𝐚𝐫𝐢𝐬𝐨𝐧

By default, 𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰 performs a shallow comparison of props. However, you can provide a custom comparison function if you need finer control over the re-rendering process.

𝐄𝐱𝐚𝐦𝐩𝐥𝐞 𝐰𝐢𝐭𝐡 𝐂𝐮𝐬𝐭𝐨𝐦 𝐂𝐨𝐦𝐩𝐚𝐫𝐢𝐬𝐨𝐧:

Image description

In this example, the compareProps function checks whether the value prop has changed. If it hasn't, the component won't re-render, even if other parts of the parent component trigger a re-render.

𝐂𝐨𝐧𝐜𝐥𝐮𝐬𝐢𝐨𝐧

𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰 is a simple yet effective tool for optimizing functional components, especially in cases where rendering is costly or the props change infrequently. By using 𝘙𝘦𝘢𝘤𝘵.𝘮𝘦𝘮𝘰, you can improve application performance by reducing unnecessary re-renders.

Top comments (0)