Preact Components — Building Reusable UI With 3kB Footprint
Learn how to create functional and class components in Preact, compose them together, and manage component trees efficiently with the 3kB library.
In this lesson, you'll build functional components, class components, and understand how Preact's component model maps to React concepts while maintaining a smaller footprint.
What You'll Learn
How to define functional and class components in Preact, pass children between them, and compose complex UIs from simple building blocks.
Why It Matters
Components are the foundation of any Preact application. Understanding both functional and class patterns lets you work with existing codebases and choose the right approach for each situation.
Real-World Use
Doda Browser's extension popup is built from 15 Preact components arranged in a tree. Each component handles a specific UI region: bookmarks, history, settings, and search.
flowchart TD
A[App] --> B[Header]
A --> C[Sidebar]
A --> D[Main Content]
C --> E[BookmarkList]
C --> F[HistoryList]
D --> G[SearchBar]
D --> H[Results]
style A fill:#673ab8,color:#fff
Functional Components
A functional component is a function that returns JSX:
import { render } from 'preact';
function Welcome({ name }) {
return <h1>Welcome, {name}!</h1>;
}
render(<Welcome name="Alice" />, document.getElementById('app'));
Output: "Welcome, Alice!" renders as an h1 heading. The function receives props as its first argument and returns Virtual Dom nodes.
Class Components
Preact also supports class components for lifecycle methods:
import { Component, render } from 'preact';
class Clock extends Component {
constructor() {
super();
this.state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return <div>Current time: {this.state.time}</div>;
}
}
render(<Clock />, document.getElementById('app'));
Output: A live clock showing the current time, updated every second. The class component manages its own state and lifecycle.
Composing Components
Components can contain other components, creating a tree structure:
function Avatar({ src, alt }) {
return <img src={src} alt={alt} style={{ width: 50, height: 50, borderRadius: '50%' }} />;
}
function UserInfo({ user }) {
return (
<div>
<Avatar src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
function App() {
const user = { name: 'Alice', email: 'alice@example.com', avatar: '/avatar.png' };
return <UserInfo user={user} />;
}
Output: A card with avatar, name, and email. The App passes a user object to UserInfo, which delegates avatar rendering to Avatar.
Children and Slots
Preact supports the children prop for nesting content:
function Card({ title, children }) {
return (
<div style={{ border: '1px solid #ddd', padding: 16, borderRadius: 8 }}>
<h2>{title}</h2>
{children}
</div>
);
}
function App() {
return (
<Card title="Notice">
<p>This is the card body content.</p>
<button>Click me</button>
</Card>
);
}
Output: A bordered card with a title and children rendered inside. The children prop captures everything between the opening and closing tags.
Common Mistakes
- Using
this.statedirectly in class components: Always usethis.setState()to update state. Direct mutationthis.state.count = 1won't trigger re-renders. - Forgetting to bind event handlers: Class methods need binding in the constructor or use arrow function class properties:
handleClick = () => {}. - Mutating props: Props are read-only. Never modify
props.somethingdirectly. Use state for mutable data. - Using
componentWillMount: Preact supportscomponentDidMountbut notcomponentWillMount. Use the constructor orcomponentDidMount. - Not using keys in lists: When rendering arrays of components, always provide a unique
keyprop to help Preact's diff algorithm track elements.
Practice Questions
What are the two types of components in Preact? Answer: Functional components (functions returning JSX) and class components (extending
Componentwith lifecycle methods).How do you pass data from a parent to a child component? Answer: Through props. The parent passes attributes like
<Child name="value" />and the child accesses them viaprops.name.What prop captures nested content between component tags? Answer: The
childrenprop. Content between<MyComp>...</MyComp>becomesprops.children.How do you update state in a class component? Answer: Call
this.setState(newState). Preact merges the new state with the existing state automatically.
Challenge
Build a comment component that renders a list of comments. Each comment has an author avatar, name, timestamp, and text. Compose at least three levels of nested components (App -> CommentList -> Comment -> Avatar).
Mini Project
Create a simple blog post layout with Header, MainContent, Sidebar, and Footer components. Pass dummy data as props and verify the component tree renders correctly.
FAQ
What's Next
Learn about Preact Props and State to understand data flow and state management in Preact applications.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro