Your next page is taking shape...

Opening Your Next Page…

Loading the guide and preparing its examples for you to explore. The page will appear here automatically when it’s ready, so you can keep this view open without refreshing.

Made for Preact. Built to be yours.

kamod-state · Typed Reducers · Preact Context

Tiny, Typed Reducer State Management for Preact

createStore and createAction with TypeScript-first action matching, Preact context providers, optional middleware, and a signals bridge — without a React runtime.

Model Meaningful State Transitions with named actions and a focused reducer. Keep one clear source of truth, then connect only the state each component needs through your chosen Preact integration. Pair it with the Component Library when building your interface. Continue with the Full Documentation for the complete package reference.


What the Package Brings

Use named actions and reducers when changes need a clear explanation. Model the events in your flow first, then decide which components read state and which dispatch actions.

Choose the Right Approach

A Local Open or Closed Control

Keep simple presentation state local to the component.

A reducer store is useful when events and shared ownership add clarity, not for every boolean.

A Shared Domain Workflow

Model named actions and derive the next state in a pure reducer.

Store domain facts; derive display labels and totals where possible instead of saving duplicates.

A Reactive View of Store Data

Select the smallest useful value with the package's Preact integration.

If a signals bridge is needed, keep one authoritative writer rather than two synchronized stores.

Typed Action Creators

createAction returns creators with .match() so reducers stay narrow and exhaustiveness-friendly.

Choose action names that describe a domain event. Keep the payload focused so a reducer can make its decision from the current state and that event without reaching into a component.

Preact Integration

createStoreContext wires stores into components with useStore, useDispatch, and useSelector entry points.

Place the store boundary around the consumers that need it. Select the state each view actually uses and keep transient interaction details local when they do not belong in the domain model.

Optional Signals Bridge

Subscribe store slices through @kamod-ch/state/signals when you already use @preact/signals in the UI.

Use a bridge when an existing signal-based view needs a store slice. Keep the store authoritative and derive the view instead of synchronizing two separately editable copies.

Installation

Start with the state model your feature needs. Install @kamod-ch/state in the workspace that owns the store, and keep Preact available when using the context integration. The first example only needs the package’s action and store APIs, so you can understand the state transition before connecting a component tree.

Choose integrations deliberately. The Preact adapter is available through @kamod-ch/state/preact; @kamod-ch/state/signals provides a bridge when your views already use signals. Review Choose the Right Approach before adding a bridge, then run the Usage Example with one action and one reducer.

Install PackagesTerminal
pnpm add @kamod-ch/state preact

Check Your Environment

Use your existing package manager and keep the peer dependencies aligned with your application. Compare package.json and your lockfile with the documentation for the version you install; add the package once at the workspace boundary that uses it.

Keep the First Change Small. Start with the usage example, run your project’s typecheck and build, then connect it to a real screen. The Package Overview helps you decide how companion libraries fit together.

Usage

Follow one event all the way through. Name it with createAction, handle it in a reducer with .match(), and pass that reducer to createStore. Dispatch the action and inspect the resulting state. Keeping this first transition small makes the action payload and reducer’s responsibility easy to see.

Add the view after the transition works. Use createStoreContext when a Preact tree needs access to the store, and choose the state each consumer actually reads. The Typed Store Example keeps the state and action contract together; Ownership and Lifetime helps you decide where that store instance belongs. Keep network work outside the reducer and model its visible pending, success and failure states explicitly.

src/example.tsx10 lines
import { createAction, createStore } from "@kamod-ch/state";

const increment = createAction("counter/increment");

const store = createStore({
  reducer: (state = { count: 0 }, action) =>
    increment.match(action) ? { count: state.count + 1 } : state,
});

store.dispatch(increment());

Read the Example

Follow the value from its definition to the interface. Each part below explains a decision to keep when adapting the example.

Name the Event

A named event describes an intention, not a particular button. Multiple controls can dispatch it without teaching the reducer about their markup. Keep naming consistent as the feature grows.

Usage PatternTypeScript
const increment = createAction("counter/increment");
Return a New Value Only for a Handled Event

The matcher selects the branch. Returning the existing state for unrelated actions protects the current value; returning a new object for the matching action makes the transition explicit. Avoid mutation or network work inside the reducer.

Usage PatternTypeScript
increment.match(action) ? { count: state.count + 1 } : state
Dispatch through the Store Boundary

A dispatch changes the model. A Preact view also needs a subscription, normally through the package's context and selector hooks. Reading a snapshot once does not turn an arbitrary component into a subscriber.

Usage PatternTypeScript
store.dispatch(increment());

Define the State and Event Contract Together

An explicit state type makes the model readable as soon as a second view needs it. A factory gives each test or server request its own store. Decide where the app owns that instance before wiring a provider around its consumers.

src/state/counter.ts12 lines
import { createAction, createStore } from "@kamod-ch/state";

export const increment = createAction("counter/increment");
type CounterState = { count: number };
type CounterAction = ReturnType<typeof increment>;

export function createCounterStore() {
  return createStore<CounterState, CounterAction>({
    reducer: (state = { count: 0 }, action) =>
      increment.match(action) ? { count: state.count + 1 } : state,
  });
}

Try the Boundaries. Create two stores and confirm that dispatching to one does not change the other. When adding asynchronous work, represent pending, success and failure deliberately and keep the effect outside the reducer. Consult the package reference for context, selectors and middleware signatures.

Integrate with Your Application

Name Actions for What Happened. Keep reducer transitions predictable and place network requests or other effects at a deliberate application boundary. This makes loading, success and failure states easier to inspect and test.

Choose the store’s lifetime explicitly: an isolated flow, a mounted application tree or a request. Avoid a shared server singleton for user-specific state. Use selectors to keep the relationship between component inputs and domain state easy to follow.

If you also use signals, define which layer owns the value before adding a bridge. Derive a view of existing state rather than maintaining two independently writable copies that can drift apart.

Choose the Owner and Lifetime

Put the store at the boundary of the workflow it represents. A page-local flow can use a page-local owner, while an app-wide session model may need a longer lifetime. For SSR and tests, factories make ownership explicit. Keep reducers deterministic so the same state and event produce the same result without depending on the clock or network.

Account for the Environment

Model asynchronous outcomes as deliberate transitions. A submit action can lead to pending, followed by success or failure; the component then renders those states. Keep the request itself outside the reducer and decide how stale results are handled if the user starts another operation or leaves the screen before it completes.

Connect the Pieces. Component-Owned Hooks — Keep transient UI behavior close to its component while the store owns the shared domain model.

Integration goal
What a good integration looks like

A useful state model explains both what happened and what the user sees next. Pair loading, success and failure transitions with visible feedback and deliberate focus behavior.

When Something Behaves Differently

Start with the smallest failing interaction. Compare a fresh page with the same page after a change or reload, and keep the package version in your reproduction.

Dispatch happens but the view does not update
Verify that the view subscribes through the appropriate context or selector API. Also check that the matching reducer branch returns a new value instead of mutating existing state.
An unrelated action resets the screen
Inspect the reducer's fallback branch. Return the current state for actions it does not handle rather than recreating the initial state.
State leaks between tests or requests
Look for a shared module-level store. Create an instance for each independent owner and verify that updates in one instance cannot affect the other.

If the behavior still differs from the documented API, Check Existing Issues before opening a report. Include the expected result, actual result, package version and a small reproduction without private application data.

API Reference

This page is a Kamod UI overview. Full API docs, middleware, testing helpers, and signals integration live on the dedicated kamod-state docs.

Use this page to understand the integration, then consult the Full API Reference on Live Docs for exact signatures and supported options. Compare those details with the version in your lockfile before adapting an example.

Explore API, Middleware, and Preact Patterns

Open the kamod-state docs for getting started, context usage, testing utilities, and the signals bridge.

  • Before Choosing an API: read its input types, return values and default behavior.
  • Before Shipping: review lifecycle or server-rendering notes for the features you use.
  • When Behavior Differs: reduce the case to a small example and include your package version in the report.
Continue with the dedicated package documentation.Open Live Docs

Accessibility Notes

When store state drives UI (dialogs, tabs, selections), keep focus management and ARIA state in sync with dispatched actions.

Before You Ship

  • Test successful, failed and cancelled transitions with representative actions.
  • Confirm that unrelated actions leave the reducer’s state intact.
  • Check that opening and closing UI through actions also preserves focus and keyboard behavior.

Review the result with Real Content and Keyboard Input. Keep visible labels, loading and error feedback, and focus behavior in sync with the state your application exposes.

Take the Guide with You

Keep the Examples, Integration Decisions and Troubleshooting Notes together in your project, or share them with a coding assistant. This reference works with any assistant; no model-specific setup is needed. Check the installed version and your project’s conventions before applying a suggestion.

Keep It HandyReady for your project
DownloadMarkdown
state-package-reference.md167 lines
# State — integration reference

createStore and createAction with TypeScript-first action matching, Preact context providers, optional middleware, and a signals bridge — without a React runtime.

Package: @kamod-ch/state

## Choose an approach

Use named actions and reducers when changes need a clear explanation. Model the events in your flow first, then decide which components read state and which dispatch actions.

### A local open or closed control

Keep simple presentation state local to the component.

A reducer store is useful when events and shared ownership add clarity, not for every boolean.

### A shared domain workflow

Model named actions and derive the next state in a pure reducer.

Store domain facts; derive display labels and totals where possible instead of saving duplicates.

### A reactive view of store data

Select the smallest useful value with the package's Preact integration.

If a signals bridge is needed, keep one authoritative writer rather than two synchronized stores.

## Installation

**Start with the state model your feature needs.** Install `@kamod-ch/state` in the workspace that owns the store, and keep Preact available when using the context integration. The first example only needs the package’s action and store APIs, so you can understand the state transition before connecting a component tree.

**Choose integrations deliberately.** The Preact adapter is available through `@kamod-ch/state/preact`; `@kamod-ch/state/signals` provides a bridge when your views already use signals. Review [Choose the Right Approach](https://ui.kamod.ch/docs/state-package/installation#choose-your-approach) before adding a bridge, then run the [Usage Example](https://ui.kamod.ch/docs/state-package/installation#usage) with one action and one reducer.

```bash
pnpm add @kamod-ch/state preact
```

## Starting example

**Follow one event all the way through.** Name it with `createAction`, handle it in a reducer with `.match()`, and pass that reducer to `createStore`. Dispatch the action and inspect the resulting state. Keeping this first transition small makes the action payload and reducer’s responsibility easy to see.

**Add the view after the transition works.** Use `createStoreContext` when a Preact tree needs access to the store, and choose the state each consumer actually reads. The [Typed Store Example](https://ui.kamod.ch/docs/state-package/installation#put-it-to-work) keeps the state and action contract together; [Ownership and Lifetime](https://ui.kamod.ch/docs/state-package/installation#state-and-lifetime) helps you decide where that store instance belongs. Keep network work outside the reducer and model its visible pending, success and failure states explicitly.

```tsx
import { createAction, createStore } from "@kamod-ch/state";

const increment = createAction("counter/increment");

const store = createStore({
  reducer: (state = { count: 0 }, action) =>
    increment.match(action) ? { count: state.count + 1 } : state,
});

store.dispatch(increment());
```

### Name the Event

A named event describes an intention, not a particular button. Multiple controls can dispatch it without teaching the reducer about their markup. Keep naming consistent as the feature grows.

```tsx
const increment = createAction("counter/increment");
```

### Return a New Value Only for a Handled Event

The matcher selects the branch. Returning the existing state for unrelated actions protects the current value; returning a new object for the matching action makes the transition explicit. Avoid mutation or network work inside the reducer.

```tsx
increment.match(action) ? { count: state.count + 1 } : state
```

### Dispatch through the Store Boundary

A dispatch changes the model. A Preact view also needs a subscription, normally through the package's context and selector hooks. Reading a snapshot once does not turn an arbitrary component into a subscriber.

```tsx
store.dispatch(increment());
```

## Define the State and Event Contract Together

An explicit state type makes the model readable as soon as a second view needs it. A factory gives each test or server request its own store. Decide where the app owns that instance before wiring a provider around its consumers.

File: src/state/counter.ts

```tsx
import { createAction, createStore } from "@kamod-ch/state";

export const increment = createAction("counter/increment");
type CounterState = { count: number };
type CounterAction = ReturnType<typeof increment>;

export function createCounterStore() {
  return createStore<CounterState, CounterAction>({
    reducer: (state = { count: 0 }, action) =>
      increment.match(action) ? { count: state.count + 1 } : state,
  });
}
```

Create two stores and confirm that dispatching to one does not change the other. When adding asynchronous work, represent pending, success and failure deliberately and keep the effect outside the reducer. Consult the package reference for context, selectors and middleware signatures.

## Ownership and environment

Put the store at the boundary of the workflow it represents. A page-local flow can use a page-local owner, while an app-wide session model may need a longer lifetime. For SSR and tests, factories make ownership explicit. Keep reducers deterministic so the same state and event produce the same result without depending on the clock or network.

Model asynchronous outcomes as deliberate transitions. A submit action can lead to pending, followed by success or failure; the component then renders those states. Keep the request itself outside the reducer and decide how stale results are handled if the user starts another operation or leaves the screen before it completes.

A useful state model explains both what happened and what the user sees next. Pair loading, success and failure transitions with visible feedback and deliberate focus behavior.

## Troubleshooting

### Dispatch happens but the view does not update

Verify that the view subscribes through the appropriate context or selector API. Also check that the matching reducer branch returns a new value instead of mutating existing state.

### An unrelated action resets the screen

Inspect the reducer's fallback branch. Return the current state for actions it does not handle rather than recreating the initial state.

### State leaks between tests or requests

Look for a shared module-level store. Create an instance for each independent owner and verify that updates in one instance cannot affect the other.

## Resources

- [Dedicated documentation](https://kamod-ch.github.io/kamod-state/) — Exact signatures, supported options and deeper examples.

- [Source & release history](https://github.com/kamod-ch/kamod-state) — Implementation, release notes and the project’s issue tracker.

- [Published package](https://www.npmjs.com/package/@kamod-ch/state) — Compare the version and peer requirements with your lockfile.

When copying or distributing source, retain the applicable license and attribution notices from the version you use.

## Companion packages

A store is the home of domain facts. Give persistence, transient interaction and human-readable messages their own clear boundaries around it.

### Signals — Remember only what should survive

[`@kamod-ch/signals`](https://ui.kamod.ch/docs/signals-package/installation)

A workflow may keep a display preference across visits without saving every transient state. Decide exactly which values can be restored and how they re-enter the domain model; avoid two authoritative writers for the same fact.

### Hooks — Leave the interface room to breathe

[`@kamod-ch/hooks`](https://ui.kamod.ch/docs/hooks-package/installation)

Keep a tooltip, temporary expansion or local focus behavior near its component. Hooks can own that presentation state while actions and selectors describe the shared workflow; every open panel does not need a reducer event.

### i18n — Translate outcomes, not stored facts

[`@kamod-ch/i18n`](https://ui.kamod.ch/docs/i18n-package/installation)

Store a stable status or error identifier, then translate its message in the consuming view. A language change should update the explanation without replaying an action, refetching a result or rewriting the underlying domain state.

## Finish one complete transition.

Follow one user action through pending, success and failure, then show each result with an Alert. Keep the request outside the reducer and make retry behavior explicit, so the view explains what the model actually knows.

[Give outcomes a clear voice](https://ui.kamod.ch/docs/alert/installation)

Try repeated dispatch, a stale response and two independently created store instances.

[All packages](https://ui.kamod.ch/docs/packages) · [The wider ecosystem](https://ui.kamod.ch/docs/ecosystem)
Display changes only the view. Copy and download include the complete Markdown reference.

Sources & Attribution

This integration guide accompanies @kamod-ch/state, maintained in the Kamod ecosystem. The Dedicated Documentation is the reference for package APIs; examples here show how those APIs fit into a Kamod UI application.

Finish One Complete Transition.

Follow one user action through pending, success and failure, then show each result with an Alert. Keep the request outside the reducer and make retry behavior explicit, so the view explains what the model actually knows.

Try repeated dispatch, a stale response and two independently created store instances.

Take the Next Useful Step

You have the pieces. Put them into one real interaction, keep its state in one place, and check the result with the content your application will actually show.

Connect the Foundation

Return to Choose Your Companion Packages to connect this reference to a working screen. Keep global CSS in one entrypoint and import only the components that screen needs.

Build the Surrounding Screen

Find a neighboring interaction in the Component Library, or start with a complete Block. Replace sample content and destinations before refining the layout; a local class change can stay with the composition.

Make the Result Hold Up

Use shared theme roles for changes that belong everywhere. Then review the whole journey: keyboard focus, long labels, narrow screens and a clear way to recover when something fails.

Keep a link to the source and note your intentional changes. Your next edit should begin with a clear decision, not another search.