memo
Memoize a functional component so that it only re-renders when its props actually change. This was previously known asReact.pure.
Signature
FunctionalComponent<P>
required
The functional component to memoize.
(prev: P, next: P) => boolean
Optional custom comparison function. Should return
true if the props are equal (skip render), or false if they are different (re-render).If not provided, a shallow comparison is performed automatically.FunctionComponent<P>
A memoized version of the component that only re-renders when props change.
Usage
Basic Memoization
Memoize a component with automatic shallow prop comparison:Custom Comparison
Provide a custom comparison function for complex props:Array Props
Compare array contents:With Hooks
Memo works seamlessly with hooks:Implementation Details
Thememo implementation in Preact:
Key Features
- Shallow Comparison: By default, uses
shallowDiffersto compare props - Custom Comparison: Accepts optional custom comparison function
- Ref Handling: Properly handles ref changes
- Display Name: Automatically generates display name for debugging
Comparison Logic
Default Shallow Comparison
When no comparer is provided,memo performs a shallow comparison:
- Any keys exist in one object but not the other
- Any values differ using strict equality (
!==)
Custom Comparer Return Value
Important: The comparer function should return:trueif props are equal (skip re-render)falseif props are different (re-render)
shouldComponentUpdate!
Performance Considerations
When to Use memo
✅ Good use cases:- Components that render frequently with the same props
- Components with expensive render calculations
- List items in a large list
- Components receiving callback props from parent
- Props change on every render anyway
- Component is already fast
- The memo overhead outweighs render cost
Measuring Performance
Type Definitions
Checking if a Component is Memoized
Best Practices
- Profile First: Use browser dev tools to identify slow components before memoizing
- Memoize Callbacks: Combine with
useCallbackfor callback props - Memoize Values: Use
useMemofor computed values passed as props - Custom Comparers: Only use custom comparers when necessary - they add overhead
- Ref Stability: Ensure ref callbacks are stable to avoid unnecessary updates