React ยท Chapter 33 of 42
React.memo
`React.memo` is a higher-order component that memoizes a component, skipping re-renders when its props haven't changed (using a shallow comparison).
It's most useful for components that render often with the same props, especially ones that are expensive to render.
Wrapping a component
`const Memoized = React.memo(MyComponent);` โ Memoized only re-renders when its props change.
Custom comparison
You can pass a second argument, a custom comparison function, if the default shallow prop comparison isn't sufficient.
Example 1 (jsx)
const ExpensiveRow = React.memo(function ExpensiveRow({ item }) {
console.log("Rendering", item.id);
return <li>{item.label}</li>;
});Output
Rendering logs only when item prop actually changesReact.memo prevents re-render when props are unchanged.
Key points
- React.memo skips re-rendering when props haven't changed.
- It performs a shallow comparison of props by default.
- Best applied to components that render often with stable props.
- Pass a custom comparator as a second argument for special cases.
๐ก Note: React.memo won't help if you're passing new object/array/function props on every render โ combine with useMemo/useCallback.
