Skip to content

Preact Components — Building Reusable UI With 3kB Footprint

DodaTech Updated 2026-06-28 4 min read

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

  1. Using this.state directly in class components: Always use this.setState() to update state. Direct mutation this.state.count = 1 won't trigger re-renders.
  2. Forgetting to bind event handlers: Class methods need binding in the constructor or use arrow function class properties: handleClick = () => {}.
  3. Mutating props: Props are read-only. Never modify props.something directly. Use state for mutable data.
  4. Using componentWillMount: Preact supports componentDidMount but not componentWillMount. Use the constructor or componentDidMount.
  5. Not using keys in lists: When rendering arrays of components, always provide a unique key prop to help Preact's diff algorithm track elements.

Practice Questions

  1. What are the two types of components in Preact? Answer: Functional components (functions returning JSX) and class components (extending Component with lifecycle methods).

  2. 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 via props.name.

  3. What prop captures nested content between component tags? Answer: The children prop. Content between <MyComp>...</MyComp> becomes props.children.

  4. 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

Can I use React class lifecycle methods in Preact?

: Yes. Preact class components support componentDidMount, componentDidUpdate, componentWillUnmount, shouldComponentUpdate, and getDerivedStateFromProps.

Do Preact components support default props?

: Yes. Use Component.defaultProps = { ... } for class components or default parameters for functional components.

Can I use higher-order components (HOCs) in Preact?

: Yes. HOCs work the same as in React. Wrap a component and return a new one with additional props or behavior.

What is `shouldComponentUpdate` in Preact?

: A lifecycle method that returns true or false. Return false to skip re-rendering when props or state haven't changed.

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