Skip to main content

memo

Memoize a functional component so that it only re-renders when its props actually change. This was previously known as React.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

The memo implementation in Preact:

Key Features

  1. Shallow Comparison: By default, uses shallowDiffers to compare props
  2. Custom Comparison: Accepts optional custom comparison function
  3. Ref Handling: Properly handles ref changes
  4. Display Name: Automatically generates display name for debugging

Comparison Logic

Default Shallow Comparison

When no comparer is provided, memo performs a shallow comparison:
This checks if:
  • 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:
  • true if props are equal (skip re-render)
  • false if props are different (re-render)
This is the opposite of 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
Avoid memo when:
  • 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

  1. Profile First: Use browser dev tools to identify slow components before memoizing
  2. Memoize Callbacks: Combine with useCallback for callback props
  3. Memoize Values: Use useMemo for computed values passed as props
  4. Custom Comparers: Only use custom comparers when necessary - they add overhead
  5. Ref Stability: Ensure ref callbacks are stable to avoid unnecessary updates

Common Patterns

Memoizing with Context

Memoizing List Items

Source

Implementation: compat/src/memo.js:1-35