Skip to main content
Base class for creating stateful, class-based components in Preact.

Signature

Type Parameters

object
default:"{}"
The props type for the component.
object
default:"{}"
The state type for the component.

Constructor

Creates a new component instance with the given props and context.

Instance Properties

props

The current props passed to the component. Includes children and optional ref.

state

The current state of the component. Should only be modified via setState().

context

Context value from the nearest Provider ancestor, or the default value.

Core Methods

setState

Updates component state and schedules a re-render. Parameters:
  • state: Object to merge into state, or updater function receiving previous state and props
  • callback: Optional function called after state update and re-render complete
Implementation: src/component.js:34

forceUpdate

Forces a synchronous re-render, bypassing shouldComponentUpdate. Parameters:
  • callback: Optional function called after re-render completes
Implementation: src/component.js:69

render

Returns the component’s virtual DOM tree. Must be implemented by subclasses.

Usage Examples

Basic Component

With TypeScript

Lifecycle Methods

shouldComponentUpdate Optimization

Error Boundaries

Context Consumer

Lifecycle Method Order

Mounting

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

Updating

  1. static getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

Unmounting

  1. componentWillUnmount()

Error Handling

  1. static getDerivedStateFromError()
  2. componentDidCatch()

Legacy Lifecycle Methods

These methods are still supported but deprecated:
  • componentWillMount() - Use componentDidMount() or constructor()
  • componentWillReceiveProps() - Use getDerivedStateFromProps() or componentDidUpdate()
  • componentWillUpdate() - Use getSnapshotBeforeUpdate() or componentDidUpdate()

Implementation Details

The Component class is implemented in src/component.js:19 as BaseComponent:

Performance Notes

  • setState uses shallow merging and batches multiple calls
  • Re-renders are scheduled asynchronously via microtasks
  • forceUpdate bypasses shouldComponentUpdate optimization
  • State updates within setState callback see the updated state
  • render - Mount components to the DOM
  • Fragment - Group multiple children
  • createContext - Create context for component tree
  • hooks - Modern alternative to class components