How to Memoize a React Component for Better Performance
In React, memoization helps prevent unnecessary re-renders of components by "remembering" their rendered output unless their props change. This improves performance, especially for components that are heavy to render or used frequently.
To memoize a component, you can use the built-in React.memo
higher-order component. Here's how it works:
import React from "react"; const MyComponent = ({ title }) => { console.log("Rendering MyComponent..."); return <h1>{title}</h1>; }; // Memoize the component export default React.memo(MyComponent);
Explanation:
React.memo
wraps your component and checks if the props have changed.- If the props are the same as the last render, React skips rendering and reuses the previous output.
- If the props have changed, the component re-renders.
When to Use React.memo
- Components that render the same output given the same props.
- Components that are pure (output only depends on props, not on internal state or context).
- In lists or grids where many similar components are rendered.
Custom Comparison Function
You can pass a custom comparison function to React.memo
to control when a component should re-render:
export default React.memo(MyComponent, (prevProps, nextProps) => { // Return true if props are equal (no re-render) // Return false if props are different (re-render) return prevProps.title === nextProps.title; });
Use this when you have complex props or need fine-grained control over re-rendering.
Key Points to Remember
- React.memo is a performance optimization. Only use it when necessary.
- It only works for functional components. Class components can use
PureComponent
instead. - It does a shallow comparison by default, not deep comparison.
- Avoid premature optimization. Measure performance before applying
React.memo
.