Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Preact

Learn Preact - 9 Code Examples & CST Typing Practice Test

Preact is a fast, lightweight JavaScript library for building user interfaces with a React-like API. It emphasizes small bundle size, performance, and compatibility with modern web standards while providing an easy transition for React developers.

View all 9 Preact code examples →
Preact Counter ComponentPreact Counter with Step IncrementPreact Counter with Max LimitPreact Counter with Auto-ResetPreact Counter with HistoryPreact Counter with Dark Mode OnlyPreact Counter with Auto-IncrementPreact Counter with Conditional ThemePreact Full Featured Counter

Learn PREACT with Real Code Examples

Updated Nov 22, 2025

Explain

Preact allows developers to create UI components using a syntax similar to React.

It offers a virtual DOM for efficient updates while keeping the library extremely small.

Preact is designed for performance-critical applications and low-resource environments.

Core Features

JSX support

Functional and class components

Hooks API

Virtual DOM diffing

Context API for state management

Basic Concepts Overview

Functional and class components

JSX templating

Virtual DOM updates

Hooks for state and effects

Component composition

Project Structure

src/components - reusable components

src/pages - app pages

src/index.js - entry point

package.json - dependencies

vite.config.js - optional bundler config

Building Workflow

Create Preact components (functional/class)

Use props and state for dynamic UI

Apply hooks (useState, useEffect, useRef)

Compose components hierarchically

Render root component using `render()`

Difficulty Use Cases

Beginner: single-page components

Intermediate: multi-component apps

Advanced: PWA with routing & state

Expert: React migration projects

Community: optimizing bundle size & performance

Comparisons

Smaller and faster than React

Easier migration from React than Vue or Angular

Better performance for low-resource apps

Smaller ecosystem than React

Compatible with React libraries via preact/compat

Versioning Timeline

2015 - Initial release

2016 - Hooks & functional components introduced

2019 - Preact X (major rewrite with hooks & context)

2021 - TypeScript and ecosystem improvements

2025 - Continued optimizations and ecosystem growth

Glossary

Virtual DOM: Efficient UI diffing mechanism

preact/compat: React compatibility layer

Functional Component: Stateless or hook-based component

Class Component: Stateful component with lifecycle methods

JSX: JavaScript syntax for HTML templates

Installation Setup

`npm install preact`

Optionally install `preact/compat` for React compatibility

Set up bundler (Vite/Webpack/Parcel)

Write components with JSX

Render components using `render()`

Environment Setup

Install Node.js

Install Preact via NPM

Configure bundler (Vite/Webpack/Parcel)

Add JSX support

Start building components

Config Files

package.json - dependencies

tsconfig.json - TypeScript support

vite.config.js - optional bundler config

index.html - main entry

src/components/ - Preact components

Cli Commands

`npm init preact` - starter project

`npm run dev` - start dev server

`npm run build` - production build

`npm test` - run tests

`npm run serve` - serve build output

Internationalization

Dynamic text via props

Integrate i18n libraries externally

RTL support via CSS

Locale-aware date/number formatting

Custom events for language change

Accessibility

Use semantic HTML

ARIA roles where appropriate

Keyboard navigation support

Focus management for interactive elements

Screen reader-friendly attributes

Ui Styling

CSS modules

Tailwind CSS

Styled-components

Vanilla CSS

Scoped inline styles

State Management

useState for local component state

useReducer for complex state

Context API for shared state

Props for parent-child communication

No heavy state library required

Data Management

Props and state for dynamic data

Context for global state

Fetch API for server data

Reactive updates trigger re-render

Integrate with Redux/Zustand if needed

Architecture

Component-based design

Virtual DOM for efficient updates

Hooks and context for state management

Declarative UI rendering

Optional compatibility layer with React ecosystem

Rendering Model

Client-side rendering

Virtual DOM diffing

Efficient state-driven updates

Declarative JSX templates

Optional server-side rendering via preact-render-to-string

Architectural Patterns

Component-based architecture

Hooks & functional components

Class components for lifecycle methods

Context for state sharing

Event-driven updates

Real World Architectures

Mobile-first SPAs

Embedded UI widgets

Interactive dashboards

Progressive web apps

Small to medium web applications

Design Principles

Ultra-lightweight

React-compatible API

Virtual DOM efficiency

Modular & composable

Performance-first mindset

Scalability Guide

Use small, focused components

Lazy-load non-critical components

Use context efficiently

Avoid unnecessary state updates

Split large apps into modules

Migration Guide

Migrate React components to Preact/compat

Replace React imports with Preact aliases

Adjust lifecycle methods if needed

Test compatibility with third-party React libraries

Optimize bundle size

Performance Notes

Ultra-small bundle (~3KB)

Fast rendering via virtual DOM

Supports server-side rendering

Efficient memory usage

Optimized diffing algorithm

Security Notes

Sanitize dynamic content in JSX

Follow general XSS best practices

Avoid passing untrusted HTML via dangerouslySetInnerHTML

Use HTTPS for API calls

Validate user input before state updates

Monitoring Analytics

Sentry for JS errors

Web performance monitoring

Custom logging for state changes

Web Vitals tracking

Third-party analytics integration

Code Quality

Use TypeScript with Preact

Unit test components

Lint JSX and JS

Follow hooks best practices

Optimize render performance

Practical Examples

Todo app with components

Navigation menu with state

Interactive data table

PWA with offline caching

Widget embedded in third-party sites

Troubleshooting

Check JSX transpilation

Ensure props and state are used correctly

Confirm virtual DOM updates as expected

Verify preact/compat compatibility

Debug hooks usage and lifecycle

Testing Guide

Unit testing with Jest

Component testing with Testing Library

E2E testing with Playwright/Cypress

Snapshot testing JSX output

Test hooks and state changes

Deployment Options

Static hosting (Netlify, Vercel, GitHub Pages)

Integration in existing web apps

Server-side rendering with preact-render-to-string

Embedding lightweight widgets

PWAs and SPA deployments

Tools Ecosystem

Preact CLI

preact/compat

Vite integration

Webpack/Parcel plugins

Storybook Preact support

Integrations

React libraries via preact/compat

Tailwind CSS

Redux or Zustand

Router libraries (preact-router)

TypeScript support

Productivity Tips

Keep components small and reusable

Use functional components and hooks

Leverage preact/compat for React libraries

Lazy-load heavy components

Optimize state updates and re-renders

Challenges

Build a Preact todo app

Create a navigation bar with state

Implement a PWA with caching

Embed a Preact widget

Migrate a small React app to Preact

Learning Path

Learn JSX and component basics

Understand functional vs class components

Learn hooks and state management

Practice component composition

Integrate preact/compat for React libraries

Skill Improvement Plan

Week 1: Component basics

Week 2: State and props

Week 3: Hooks and lifecycle

Week 4: PWA & router integration

Week 5: Performance optimization

Interview Questions

What is Preact and how does it differ from React?

Explain preact/compat usage.

How does Preact achieve a small bundle size?

What hooks does Preact support?

How do you render Preact components to HTML?

Cheat Sheet

`import { h, render, Component } from 'preact'` - core imports

`render(<App />, document.body)` - render root component

`function MyComp(props) {}` - functional component

`class MyComp extends Component {}` - class component

`useState`, `useEffect` - hooks

Books

Mastering Preact

Preact for React Developers

Building PWAs with Preact

Reactive UI with Preact

Modern Web Apps with Preact

Tutorials

Preact official guide

Fireship Preact crash course

Frontend Masters Preact course

Net Ninja Preact series

Building PWAs with Preact tutorial

Official Docs

https://preactjs.com/

https://preactjs.com/guide/v10/getting-started

Community Links

Preact GitHub repository

Preact Discord

Reddit r/preactjs

Stack Overflow Preact tag

Preact CLI community

Community Support

Preact GitHub repository

Preact Discord

Reddit r/preactjs

Stack Overflow Preact tag

Preact CLI community

Monetization

Web app products

Widget SaaS

Consulting for performance optimization

Preact component libraries

Freelance UI development

Future Roadmap

Enhanced SSR support

Better TypeScript tooling

Continued performance optimization

Stronger ecosystem & tooling

Improved React compatibility

When Not To Use

Full-stack frameworks

Complex enterprise apps with heavy ecosystem dependencies

Apps requiring full React features out-of-the-box

Projects needing rich official tooling

Large-scale state-heavy applications

Final Summary

Preact is a lightweight, fast React alternative.

It uses a virtual DOM and supports components with hooks.

Highly performant and small in bundle size (~3KB).

Compatible with most React libraries via preact/compat.

Ideal for small-to-medium web apps, PWAs, and widgets.

Faq

Is Preact a framework?

No, it’s a lightweight UI library similar to React.

Can Preact use React libraries?

Yes, via preact/compat.

Is Preact good for small apps?

Excellent, due to small size and fast rendering.

Does Preact include routing?

No, use preact-router or other libraries.

Is Preact beginner-friendly?

Yes, if familiar with React concepts and JSX.

Code Sample Descriptions

1

Preact Counter Component

import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';

function Counter() {
    const [count, setCount] = useState(0);
    const [isDark, setIsDark] = useState(false);

    useEffect(() => {
        const savedCount = localStorage.getItem('count');
        if (savedCount) setCount(parseInt(savedCount, 10));
    }, []);

    useEffect(() => {
        localStorage.setItem('count', count.toString());
    }, [count]);

    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <div>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
        <button onClick={() => setIsDark(!isDark)}>Switch to {isDark ? 'Light' : 'Dark'} Theme</button>
        </div>
    );
}

export default Counter;

Basic Preact counter with dark/light theme toggle.

Let’s Try →
2

Preact Counter with Step Increment

import { h } from 'preact';
import { useState } from 'preact/hooks';

function StepCounter() {
    const [count, setCount] = useState(0);
    const step = 2;
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + step)}>+</button>
        <button onClick={() => setCount(count - step)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

export default StepCounter;

Counter increments/decrements by a step value using Preact.

Let’s Try →
3

Preact Counter with Max Limit

import { h } from 'preact';
import { useState } from 'preact/hooks';

function MaxCounter() {
    const [count, setCount] = useState(0);
    const max = 5;
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => count < max && setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

export default MaxCounter;

Stops incrementing after a maximum count is reached.

Let’s Try →
4

Preact Counter with Auto-Reset

import { h } from 'preact';
import { useState } from 'preact/hooks';

function AutoResetCounter() {
    const [count, setCount] = useState(0);
    const threshold = 10;
    const increment = () => setCount(c => (c + 1 > threshold ? 0 : c + 1));
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={increment}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

export default AutoResetCounter;

Automatically resets when counter exceeds threshold.

Let’s Try →
5

Preact Counter with History

import { h } from 'preact';
import { useState } from 'preact/hooks';

function HistoryCounter() {
    const [count, setCount] = useState(0);
    const [history, setHistory] = useState([]);
    const increment = () => { setCount(count + 1); setHistory([...history,'Increment']); };
    const decrement = () => { setCount(count - 1); setHistory([...history,'Decrement']); };
    const reset = () => { setCount(0); setHistory([...history,'Reset']); };
    return (
        <div>
        <h2>Counter: {count}</h2>
        <div>History: {history.join(', ')}</div>
        <button onClick={increment}>+</button>
        <button onClick={decrement}>-</button>
        <button onClick={reset}>Reset</button>
        </div>
    );
}

export default HistoryCounter;

Tracks increment/decrement history.

Let’s Try →
6

Preact Counter with Dark Mode Only

import { h } from 'preact';
import { useState } from 'preact/hooks';

function DarkModeCounter() {
    const [isDark, setIsDark] = useState(false);
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: 0</h2>
        <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
        </div>
    );
}

export default DarkModeCounter;

Static counter with only dark/light theme toggle.

Let’s Try →
7

Preact Counter with Auto-Increment

import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';

function AutoIncrementCounter() {
    const [count, setCount] = useState(0);
    useEffect(() => { const interval = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(interval); }, []);
    return <h2>Counter: {count}</h2>;
}

export default AutoIncrementCounter;

Automatically increments counter every second.

Let’s Try →
8

Preact Counter with Conditional Theme

import { h } from 'preact';
import { useState } from 'preact/hooks';

function ConditionalThemeCounter() {
    const [count, setCount] = useState(0);
    const isDark = count % 2 === 0;
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

export default ConditionalThemeCounter;

Theme changes automatically based on even/odd counter value.

Let’s Try →
9

Preact Full Featured Counter

import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';

function FullCounter() {
    const [count, setCount] = useState(0);
    const [history, setHistory] = useState([]);
    const [isDark, setIsDark] = useState(false);
    const step = 2, max = 10;
    useEffect(() => { const interval = setInterval(() => { setCount(c => { let n = c + step; if(n > max) n = 0; setHistory(h => [...h,'Auto Increment']); return n; }); },1000); return () => clearInterval(interval); }, []);
    const increment = () => { setCount(c => c + step); setHistory(h => [...h,'Increment']); };
    const decrement = () => { setCount(c => c - step); setHistory(h => [...h,'Decrement']); };
    const reset = () => { setCount(0); setHistory(h => [...h,'Reset']); };
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <div>History: {history.join(', ')}</div>
        <button onClick={increment}>+</button>
        <button onClick={decrement}>-</button>
        <button onClick={reset}>Reset</button>
        <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
        </div>
    );
}

export default FullCounter;

Combines step increment, max limit, auto-reset, history, auto-increment, and theme toggle.

Let’s Try →

Frequently Asked Questions about Preact

What is Preact?

Preact is a fast, lightweight JavaScript library for building user interfaces with a React-like API. It emphasizes small bundle size, performance, and compatibility with modern web standards while providing an easy transition for React developers.

What are the primary use cases for Preact?

Small to medium web applications. Mobile-first web apps. Interactive widgets and components. Progressive web apps (PWAs). High-performance client-side rendering

What are the strengths of Preact?

Ultra-small and fast. Easy migration from React. Great for performance-critical apps. Strong ecosystem via preact/compat. Supports modern tooling like Vite and Webpack

What are the limitations of Preact?

Not a full-stack framework. Smaller community than React. Limited built-in routing or state libraries. Some React libraries may need preact/compat. Less official documentation than React

How can I practice Preact typing speed?

CodeSpeedTest offers 9+ real Preact code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.