Skip to main content

PureComponent

A component class with a predefined shouldComponentUpdate implementation that performs shallow comparison of props and state.

Signature

Usage

Basic Example

Extend PureComponent instead of Component:

With State

PureComponent also compares state changes:

TypeScript

Type your props and state:

Implementation Details

The PureComponent implementation in Preact:

Shallow Comparison

The shallowDiffers function checks if objects differ:
This returns 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 ✅

  1. Components with simple props: Props that are primitives or stable references
  2. Frequently updated lists: List items that receive the same props often
  3. Performance optimization: Components that re-render unnecessarily

Problematic Cases ❌

  1. Props with new objects: Creating new objects on every render defeats the purpose
  1. Props with new arrays: New array references cause unnecessary re-renders
  1. Props with inline functions: New function references on every render

PureComponent vs Component

PureComponent vs memo

  • PureComponent: For class components
  • memo: For functional components
Both provide similar optimization but for different component types.

Overriding shouldComponentUpdate

You can override shouldComponentUpdate in a PureComponent for custom logic:
Note: This defeats the purpose of PureComponent. Use regular Component instead.

Common Patterns

List Items

With Context

Identifying Pure Components

Check if a component is a PureComponent:

Best Practices

  1. Stable Props: Ensure props are stable references or primitives
  2. Avoid Inline Objects: Don’t create new objects in render
  3. Avoid Inline Functions: Use class methods or memoized callbacks
  4. Measure Performance: Profile before and after to ensure it helps
  5. Consider Hooks: For new code, consider using functional components with memo instead

Migration to Functional Components

Modern Preact/React development favors functional components with hooks:

Source

Implementation: compat/src/PureComponent.js:1-17