Preact

From j4flmao/agent-skills · View interactive version

Preact is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Preact, Preact signals, preact/compat, Preact vs React, Preact SSR or cutting bundle size with a React-compatible library. Produces Preact components, signal-based state and compat aliasing. Not for React-specific architecture (use react-architecture).

How to use this skill

Skill file

Preact

Purpose

Build ultra-lightweight Preact applications using signals for reactive state, compat layer for React interop, and hooks for component logic — all under 3kB.

Agent Protocol

Trigger

Exact user phrases: "Preact setup", "Preact signal", "Preact hooks", "Preact project", "Preact vs React", "Preact SSR", "preact app".

Input Context

Before activating, verify:

Output Artifact

No file output. Produces code snippets, config examples, and structural guidance as text.

Response Format

Config:

// vite.config.ts
import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'
export default defineConfig({ plugins: [preact()] })

Code: show component, signal, and hook definitions inline. No import statements.

No preamble. No postamble. No explanations. Compress output — why use many token when few do trick.

Completion Criteria

Max Response Length

~4096 tokens.

Architecture Decision Trees

State Management Decision

What type of state?
  Local UI state (toggle, input) -> useSignal() from @preact/signals
  Shared across few siblings -> Props lifting + signals
  Global application state -> Signals in a shared module file
  Server/async state -> useSWR or TanStack Query (via compat)
  Complex form state -> useReducer from preact/hooks

React library using state? -> Use preact/compat aliasing + their API

React Compatibility Decision

Does the project use React ecosystem libraries?
  No -> Use Preact natively (smallest bundle)
  Yes -> What libraries?
    React Router -> preact/compat aliasing works
    TanStack Query -> preact/compat aliasing works
    Radix UI -> preact/compat may have issues — test first
    Framer Motion -> Known compat issues — consider alternatives

Workflow

Step 1: Setup with Vite

// vite.config.ts
import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'

export default defineConfig({
  plugins: [preact()]
})
// src/main.tsx
import { render } from 'preact'
import { App } from './app'

render(<App />, document.getElementById('app')!)

Step 2: Signals for State

import { signal, computed } from '@preact/signals'

const count = signal(0)
const doubled = computed(() => count.value * 2)

function Counter() {
  return (
    <div>
      <p>Count: {count}</p>
      <p>Doubled: {doubled}</p>
      <button onClick={() => count.value++}>+1</button>
    </div>
  )
}

Step 3: Signal Patterns

// Global signals in module
// store/cart.ts
import { signal, computed } from '@preact/signals'

export const cartItems = signal<CartItem[]>([])
export const cartCount = computed(() => cartItems.value.reduce((sum, i) => sum + i.qty, 0))
export const cartTotal = computed(() => cartItems.value.reduce((sum, i) => sum + i.price * i.qty, 0))

export function addItem(item: CartItem) {
  cartItems.value = [...cartItems.value, item]
}

// Signals with side effects
import { effect } from '@preact/signals'
effect(() => {
  console.log('Cart updated:', cartItems.value)
  localStorage.setItem('cart', JSON.stringify(cartItems.value))
})

Step 4: Hooks (React-compatible)

import { useState, useEffect, useMemo } from 'preact/hooks'

function Timer() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const id = setInterval(() => setSeconds(s => s + 1), 1000)
    return () => clearInterval(id)
  }, [])

  return <div>{seconds}s elapsed</div>
}

Step 5: Preact Compat (React interop)

// Replace React imports with preact/compat
import React from 'preact/compat'
import ReactDOM from 'preact/compat'
// Or in vite.config:
// resolve: { alias: { react: 'preact/compat', 'react-dom': 'preact/compat' } }

Step 6: SSR

import { render } from 'preact-render-to-string'
import { App } from './app'

const html = render(<App />)
// Inject into HTML template and serve

Step 7: Code Splitting

import { lazy, Suspense } from 'preact/compat'

const Dashboard = lazy(() => import('./dashboard'))
const Settings = lazy(() => import('./settings'))

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Dashboard />
    </Suspense>
  )
}

Common Pitfalls

  1. Using ReactDOM APIs: Preact uses render() from preact, not ReactDOM.createRoot().
  2. Missing compat alias: Without preact/compat aliasing, React-ecosystem libraries import React directly.
  3. Signals in JSX without values: {count} in JSX works (automatic .value access), but in hooks/effects use count.value.
  4. Class components: Preact supports them via compat, but functional + hooks + signals is preferred.
  5. Over-using compat: Using preact/compat loses the bundle-size benefit of Preact. Use native Preact APIs when possible.
  6. Switching from useState to signals mid-project: Mixed state patterns cause confusion. Pick one per feature.
  7. Not tree-shaking compat: compat adds ~2KB — only add it when needed.
  8. Forgetting SSR hydration: preact-render-to-string on server, hydrate on client with hydrate().

Best Practices

Compared With

| Aspect | Preact | React | SolidJS |

|--------|--------|-------|---------|

| Bundle size | ~3KB | ~45KB | ~8KB |

| Signals | Built-in (@preact/signals) | External | Built-in (createSignal) |

| VDOM | Yes, lightweight | Full | No (compiled) |

| React compat | preact/compat | Native | N/A |

| Hooks | Compatible subset | Full | Different API |

| SSR | preact-render-to-string | react-dom/server | solid-ssr |

Preact vs React

Preact is a React-compatible library at 1/15th the size. It supports most React APIs (hooks, JSX, Context) but lacks React 18's concurrent features and some edge cases. Use Preact when bundle size is critical and advanced React features are not needed.

Preact vs SolidJS

Both are lightweight alternatives to React. SolidJS avoids VDOM entirely for fine-grained updates; Preact keeps a lightweight VDOM for React compatibility. Preact is the drop-in replacement; SolidJS requires rewriting components.

Performance

Bundle Size Advantage

Rendering Performance

Optimization Techniques

Testing Strategies

Unit Testing with Vitest

import { render, screen, fireEvent } from '@testing-library/preact'
import { Counter } from './Counter'

test('renders counter and increments', () => {
  render(<Counter />)
  expect(screen.getByText('Count: 0')).toBeTruthy()
  fireEvent.click(screen.getByRole('button'))
  expect(screen.getByText('Count: 1')).toBeTruthy()
})

Signal Testing

import { signal, computed } from '@preact/signals'

test('signal computed values', () => {
  const count = signal(0)
  const doubled = computed(() => count.value * 2)
  expect(doubled.value).toBe(0)
  count.value = 5
  expect(doubled.value).toBe(10)
})

Key Testing Practices

Migration Patterns

From React to Preact

| React | Preact |

|-------|--------|

| import React from 'react' | import { h } from 'preact' or compat |

| ReactDOM.createRoot().render() | render() from preact |

| useState | useState from preact/hooks or signals |

| createContext | createContext from preact or signals |

| React.lazy | lazy() from preact/compat |

| React.memo | memo() from preact/compat |

Migration steps: 1) Install preact + @preact/preset-vite, 2) Add alias in vite.config, 3) Replace react-dom imports with preact, 4) Add preact/compat for remaining React libs, 5) Verify bundle size reduction.

From Vue/Options API to Preact

| Vue Concept | Preact Equivalent |

|-------------|-------------------|

| ref() | signal() |

| computed() | computed() from @preact/signals |

| watch() | effect() from @preact/signals |

| v-if | {condition && <Component/>} |

| v-for | {items.map(i => <Item />)} |

| Props | Component props argument |

Build and Bundle Considerations

Tooling

  1. Preact DevTools browser extension — inspect component tree, hooks, signals.
  2. @preact/preset-vite — official Vite preset with HMR and alias config.
  3. preact-render-to-string — SSR rendering for Preact.
  4. @testing-library/preact — component testing utilities.
  5. preact-ssr-prepass — data prefetching for SSR (Apollo, TanStack Query).
  6. preact-iso — routing and lazy loading for Preact SPA without compat.
  7. preact-hooks-testing-library — hook testing utilities.
  8. Size comparison: npx preact size compares Preact vs React bundle size.

Ecosystem

Preact-Compatible React Libraries

| Library | Compat Status |

|---------|---------------|

| React Router | Full compat |

| TanStack Query | Full compat |

| Zustand | Full compat |

| React Hook Form | Mostly works |

| Radix UI | Some issues |

| Framer Motion | Known issues |

Preact-Native Libraries

Rules

References

Handoff

No artifact produced.

Next skill: preact-ssr (if SSR needed) or frontend-testing.

Carry forward: signal-based reactivity, hooks conventions, tiny-bundle mindset.

Implementation Patterns

Signal-Based State

import { signal, computed, effect, Signal } from '@preact/signals';

// Reactive state
const count = signal(0);
const name = signal('world');

// Computed values (auto-derived)
const greeting = computed(() => `Hello, ${name.value}!`);
const doubled = computed(() => count.value * 2);

// Effects (reactions to state changes)
effect(() => {
  console.log(`Count changed to: ${count.value}`);
});

// In a component
function Counter() {
  return (
    <div>
      <p>{greeting.value}</p>
      <p>Count: {count.value} (doubled: {doubled.value})</p>
      <button onClick={() => count.value++}>+</button>
      <button onClick={() => count.value--}>-</button>
    </div>
  );
}

Optimized Component Pattern

import { h, Fragment, ComponentChildren } from 'preact';
import { useRef, useCallback, useEffect } from 'preact/hooks';

// Use memo for expensive renders
import { memo } from 'preact/compat';

interface ListItemProps {
  id: string;
  label: string;
  onSelect: (id: string) => void;
}

const ListItem = memo(({ id, label, onSelect }: ListItemProps) => {
  const handleClick = useCallback(() => onSelect(id), [id, onSelect]);
  return <li onClick={handleClick}>{label}</li>;
});

// Portal integration
import { createPortal } from 'preact/compat';

function Modal({ children }: { children: ComponentChildren }) {
  const container = useRef(document.getElementById('modal-root')!);
  return createPortal(<div class="modal-overlay">{children}</div>, container.current);
}

// Suspense-compatible lazy loading
import { lazy, Suspense } from 'preact/compat';

const HeavyComponent = lazy(() => import('./heavy-component'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <HeavyComponent />
    </Suspense>
  );
}

Anti-Patterns

| Anti-Pattern | Why It Fails | Correct Approach |

|---|---|---|

| Using compat for everything | Bundle grows to React size | Use Preact APIs directly, compat for exceptions |

| Signals everywhere | Overkill for simple local state | useState for component-local, signals for shared |

| Not aliasing in bundler | Importing react instead of preact | Configure resolve.alias in bundler |

| Class components with compat | Unnecessary weight | Functional components + hooks |

| Mixing preact/compat and preact/hooks | Hook compatibility issues | Consistently use one or the other |

Performance Optimization

Security Considerations

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.