1. Home
  2. /
  3. Preact
  4. /
  5. Counter Component

Counter Component - Preact Typing CST Test

Loading…

Counter Component — Preact Code

Basic Preact counter with dark/light theme toggle.

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;

Preact Language Guide

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.

Primary Use Cases

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

Notable Features

  • ▸Small bundle size (~3KB gzipped)
  • ▸React-compatible API
  • ▸Fast virtual DOM rendering
  • ▸Component-based architecture
  • ▸Optional ecosystem add-ons (preact/compat)

Origin & Creator

Created by Jason Miller and first released in 2015, Preact was designed as a lightweight alternative to React for high-performance web applications.

Industrial Note

Preact excels in projects where bundle size, speed, and React compatibility are crucial, such as mobile-first web apps, embedded widgets, and highly interactive UIs.

More Preact Typing Exercises

Preact 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

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher