Component types
Preact supports two types of components:- Functional components
- Class components
Functional components are simple JavaScript functions that accept props and return JSX.This is the recommended approach for most components. They are simpler, easier to test, and work seamlessly with hooks.
The Component class
Preact exports aBaseComponent class (aliased as Component) that provides core functionality for class-based components. Here’s how it’s defined in src/component.js:19:
setState()
Updates component state and schedules a re-render:forceUpdate()
Immediately triggers a re-render, bypassingshouldComponentUpdate():
Props
Props (short for “properties”) are arguments passed to components. They are read-only and flow down from parent to child.Props in class components
In class components, props are available viathis.props:
State
State is private data managed within a component. When state changes, the component re-renders.State in class components
Here’s a real example from Preact’s demo code (demo/todo.jsx:5):
The
render() method can destructure both props and state from its arguments for cleaner code.Updating state
You can pass an object or a function tosetState():
Functional vs class components
Here’s the same component implemented both ways:- Functional (with hooks)
- Class-based
Real-world example
Here’s a complete example from Preact’s demo showing both component types working together (demo/context.jsx:5):
This example demonstrates prop passing, state management, lifecycle methods, and component composition.
Component render queue
When you callsetState() or forceUpdate(), Preact doesn’t immediately re-render the component. Instead, it adds the component to a render queue (src/component.js:185):