PureComponent
A component class with a predefinedshouldComponentUpdate implementation that performs shallow comparison of props and state.
Signature
Usage
Basic Example
ExtendPureComponent instead of Component:
With State
PureComponent also compares state changes:
TypeScript
Type your props and state:Implementation Details
ThePureComponent implementation in Preact:
Shallow Comparison
TheshallowDiffers function checks if objects differ:
true if:
- Any keys exist in one object but not the other
- Any values differ using strict equality (
!==)
When to Use PureComponent
Good Use Cases ✅
- Components with simple props: Props that are primitives or stable references
- Frequently updated lists: List items that receive the same props often
- Performance optimization: Components that re-render unnecessarily
Problematic Cases ❌
- Props with new objects: Creating new objects on every render defeats the purpose
- Props with new arrays: New array references cause unnecessary re-renders
- Props with inline functions: New function references on every render
PureComponent vs Component
| Feature | Component | PureComponent |
|---|---|---|
shouldComponentUpdate | Not implemented | Shallow comparison |
| Re-renders | On any setState() or prop change | Only when props/state differ |
| Performance | Baseline | Faster for stable props |
| Use case | Most components | Frequently updated components |
PureComponent vs memo
- PureComponent: For class components
- memo: For functional components
Overriding shouldComponentUpdate
You can overrideshouldComponentUpdate in a PureComponent for custom logic:
PureComponent. Use regular Component instead.
Common Patterns
List Items
With Context
Identifying Pure Components
Check if a component is aPureComponent:
Best Practices
- Stable Props: Ensure props are stable references or primitives
- Avoid Inline Objects: Don’t create new objects in render
- Avoid Inline Functions: Use class methods or memoized callbacks
- Measure Performance: Profile before and after to ensure it helps
- Consider Hooks: For new code, consider using functional components with
memoinstead