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-hooks · Preact-First · Typed · Tree-Shakeable

Ship Preact Features Faster with Production-Ready Hooks

A Preact-first hook library inspired by ahooks — state, lifecycle, browser, and async helpers with zero runtime dependencies beyond Preact.

Start with One Behavior Your Screen Needs: a toggle, a counter or a browser preference. Keep the hook close to the component that owns it, then compose its state with your existing controls. Pair it with the Component Library when building your interface. Continue with the Full Documentation for the complete package reference.


What the Package Brings

Reach for a hook when a component needs reusable behavior: a boolean state, a bounded counter or a browser preference. Keep the visual control in Kamod UI and the behavior in the hook.

Choose the Right Approach

One Component's Interaction

Start with useToggle or useCounter and let the component own the state.

Avoid a shared store just to open one panel or change one quantity.

A Browser Preference

Use useLocalStorageState when a value should survive reloads.

Validate stored data and choose a safe default; persistence is not input validation.

Browser or Asynchronous Behavior

Pick the dedicated hook after reviewing its lifecycle and options.

Check cleanup and stale results when the component unmounts or its inputs change.

Preact-First

Built for Preact hooks, not React-compat afterthoughts. Import what you need and keep bundles lean.

Start with a single component and let it own the hook's lifetime. This keeps independent instances independent and makes mounting, resetting and cleanup easier to reason about.

Tree-Shakeable

ESM package with optional subpath imports like @kamod-ch/hooks/useToggle for tight production builds.

Choose an import convention your team can follow consistently. Check the production output before changing imports for bundle-size reasons; a smaller-looking import is not itself a measurement.

Demo-Backed Docs

Every hook ships with interactive demos and copy-ready source on the dedicated live docs site.

Use a demo to explore the normal path, then try the boundary that matters to your screen: an empty value, a fast repeated action or an unmount while work is pending.

Installation

Add behavior where your screen needs it. Install @kamod-ch/hooks in the application workspace that will import it, with Preact available as its peer dependency. If your app already uses Preact, keep that setup; these hooks work alongside your existing components. The package supplies behavior, while your controls and styles still come from your application.

Choose an import style you can repeat. The package root provides named imports such as useToggle, useCounter and useLocalStorageState. Documented subpaths such as @kamod-ch/hooks/useToggle provide a default import when you prefer a focused entry point. Both styles are supported; check the built output before choosing one for bundle-size reasons. Continue with the Usage Example, or review Versions and Peer Dependencies if an import does not resolve.

Install PackagesTerminal
pnpm add @kamod-ch/hooks 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

Start with one behavior, then connect the control. Use useToggle for an on/off value, useCounter for a quantity with optional minimum and maximum bounds, and useLocalStorageState for a preference that should survive a reload. Each name links to its implementation so you can inspect the supported options and returned actions before adapting it.

Read the value; call its actions from an event. The example groups the three hooks in useExampleState, a small custom hook you can call at the top level of a Preact component. Read on, count and theme when rendering; call toggle(), inc() or setTheme(nextTheme) from the relevant event handler. Keep a visible label beside the value so a changed state is understandable.

Try one change at a time. Follow Read the Example to unpack the return values, then build the Bounded Quantity Control. For a saved preference, choose a specific storage key and test both a fresh visit and a reload; defaultValue supplies a starting value, not validation for previously stored data. The Environment Notes explain where browser-backed behavior needs extra care.

src/example.tsx8 lines
import { useToggle, useCounter, useLocalStorageState } from "@kamod-ch/hooks";

export function useExampleState() {
  const [on, { toggle }] = useToggle(false);
  const [count, { inc }] = useCounter(0);
  const [theme, setTheme] = useLocalStorageState("theme", { defaultValue: "dark" });
  return { on, toggle, count, inc, theme, setTheme };
}

Read the Example

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

Separate the Value from Its Actions

The first item describes what to render. The second contains operations that change it. Call the hook at the top level of a component or custom hook; call toggle from the event handler, not while rendering.

Usage PatternTypeScript
const [on, { toggle }] = useToggle(false);
Make the Limits Part of the Behavior

Put the bounds in the hook and reflect them in the controls. A disabled button explains the boundary visually, while the hook keeps programmatic changes inside the same range.

Usage PatternTypeScript
const [count, { inc, dec, reset }] = useCounter(1, { min: 1, max: 5 });
Choose a Default for an Empty Browser

The second argument is an options object. A default is used when no saved value exists; it is not a validation rule for old data. Check stored values before treating them as a restricted theme name.

Usage PatternTypeScript
const [theme, setTheme] = useLocalStorageState("theme", { defaultValue: "dark" });

Connect a Bounded Quantity Control

This example keeps behavior local and uses the same Kamod buttons as the rest of the interface. The disabled states explain the limits, and reset returns to the starting quantity. Render it twice to see that each instance owns its own count.

src/components/Quantity.tsx14 lines
import { useCounter } from "@kamod-ch/hooks";
import { Button } from "@kamod-ch/ui";

export function Quantity() {
  const [count, { inc, dec, reset }] = useCounter(1, { min: 1, max: 5 });
  return (
    <div role="group" aria-label="Quantity" class="flex flex-wrap items-center gap-2">
      <Button variant="outline" disabled={count === 1} onClick={() => dec()}>Remove one</Button>
      <output aria-live="polite">{count}</output>
      <Button variant="outline" disabled={count === 5} onClick={() => inc()}>Add one</Button>
      <Button variant="ghost" onClick={reset}>Reset</Button>
    </div>
  );
}

Try the Boundaries. Try the minimum, maximum and reset paths with a keyboard. When this becomes a cart control, send the intended quantity through your application boundary and handle server rejection separately; a local count is not proof of available stock.

Integrate with Your Application

Separate Behavior from Presentation. A hook can own the value or lifecycle while a button, field or dialog supplies the interface. Keep labels, disabled states and keyboard behavior in the component rather than recreating them inside each consumer.

Call hooks consistently at the top level of your component. Check each hook’s return types and cleanup behavior before combining it with an effect; avoid a second listener or subscription for work the hook already handles.

For browser-backed behavior, review the first server render and the first client render separately. Test storage access, viewport changes and unmounting in the environment where the component will actually run.

Choose the Owner and Lifetime

Start with the smallest owner that needs the behavior. Move a hook into a custom hook when several components need the same logic, not simply because a file is long. Sharing the function does not share its state: separate calls still represent separate instances. Lift ownership only when the product requires synchronized values.

Account for the Environment

Browser hooks and server rendering have different timing. Keep direct access to window, document and storage out of server render paths. Prefer a stable initial render and apply browser-only information after mount. For asynchronous interactions, decide what the user sees while a request is pending and when a later request replaces it.

Connect the Pieces. Persisted Signals — Compare persistent, shared reactive values with component-owned hook state before choosing a second state owner.

Integration goal
What a good integration looks like

A reusable interaction should preserve its behavior when the surrounding markup changes. Keep hook ownership stable while adjusting buttons, labels and layout.

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.

The value resets unexpectedly
Check whether a changing key or a conditional parent unmounts the component. Local state belongs to that mounted instance; moving the visual control can change its lifetime.
The saved preference has an unexpected type
Inspect old storage values and your serializer. TypeScript describes current code, not historical browser data. Test fresh storage and an older value before deciding on a migration.
An interaction repeats or finishes late
Look for listeners, timers or requests created outside the hook's lifecycle. Verify cleanup when navigating away and rapid repeated input; do not hide the issue by suppressing all errors.

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. The full API, categorized hook tables, and TypeScript signatures live on the dedicated kamod-hooks 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.

Browse All 78 Hooks with Live Demos

Open the full kamod-hooks docs for getting started, migration from ahooks, and every interactive demo.

  • 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

Pair hooks that drive UI (for example toggles, focus, and viewport observers) with clear labels, keyboard affordances, and semantic controls in your components.

Before You Ship

  • Exercise both sides of a toggle and the boundaries of counters.
  • Unmount and remount the component; check that timers or listeners do not accumulate.
  • Use semantic controls and expose state through visible labels and the appropriate ARIA attributes.

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
hooks-package-reference.md175 lines
# Hooks — integration reference

A Preact-first hook library inspired by ahooks — state, lifecycle, browser, and async helpers with zero runtime dependencies beyond Preact.

Package: @kamod-ch/hooks

## Choose an approach

Reach for a hook when a component needs reusable behavior: a boolean state, a bounded counter or a browser preference. Keep the visual control in Kamod UI and the behavior in the hook.

### One component's interaction

Start with useToggle or useCounter and let the component own the state.

Avoid a shared store just to open one panel or change one quantity.

### A browser preference

Use useLocalStorageState when a value should survive reloads.

Validate stored data and choose a safe default; persistence is not input validation.

### Browser or asynchronous behavior

Pick the dedicated hook after reviewing its lifecycle and options.

Check cleanup and stale results when the component unmounts or its inputs change.

## Installation

**Add behavior where your screen needs it.** Install `@kamod-ch/hooks` in the application workspace that will import it, with Preact available as its peer dependency. If your app already uses Preact, keep that setup; these hooks work alongside your existing components. The package supplies behavior, while your controls and styles still come from your application.

**Choose an import style you can repeat.** The package root provides named imports such as `useToggle`, `useCounter` and `useLocalStorageState`. Documented subpaths such as `@kamod-ch/hooks/useToggle` provide a default import when you prefer a focused entry point. Both styles are supported; check the built output before choosing one for bundle-size reasons. Continue with the [Usage Example](https://ui.kamod.ch/docs/hooks-package/installation#usage), or review [Versions and Peer Dependencies](https://ui.kamod.ch/docs/packages#package-installation) if an import does not resolve.

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

## Starting example

**Start with one behavior, then connect the control.** Use `useToggle` for an on/off value, `useCounter` for a quantity with optional minimum and maximum bounds, and `useLocalStorageState` for a preference that should survive a reload. Each name links to its implementation so you can inspect the supported options and returned actions before adapting it.

**Read the value; call its actions from an event.** The example groups the three hooks in `useExampleState`, a small custom hook you can call at the top level of a Preact component. Read `on`, `count` and `theme` when rendering; call `toggle()`, `inc()` or `setTheme(nextTheme)` from the relevant event handler. Keep a visible label beside the value so a changed state is understandable.

**Try one change at a time.** Follow [Read the Example](https://ui.kamod.ch/docs/hooks-package/installation#read-the-example) to unpack the return values, then build the [Bounded Quantity Control](https://ui.kamod.ch/docs/hooks-package/installation#put-it-to-work). For a saved preference, choose a specific storage key and test both a fresh visit and a reload; `defaultValue` supplies a starting value, not validation for previously stored data. The [Environment Notes](https://ui.kamod.ch/docs/hooks-package/installation#environment-boundaries) explain where browser-backed behavior needs extra care.

```tsx
import { useToggle, useCounter, useLocalStorageState } from "@kamod-ch/hooks";

export function useExampleState() {
  const [on, { toggle }] = useToggle(false);
  const [count, { inc }] = useCounter(0);
  const [theme, setTheme] = useLocalStorageState("theme", { defaultValue: "dark" });
  return { on, toggle, count, inc, theme, setTheme };
}
```

### Separate the Value from Its Actions

The first item describes what to render. The second contains operations that change it. Call the hook at the top level of a component or custom hook; call toggle from the event handler, not while rendering.

```tsx
const [on, { toggle }] = useToggle(false);
```

### Make the Limits Part of the Behavior

Put the bounds in the hook and reflect them in the controls. A disabled button explains the boundary visually, while the hook keeps programmatic changes inside the same range.

```tsx
const [count, { inc, dec, reset }] = useCounter(1, { min: 1, max: 5 });
```

### Choose a Default for an Empty Browser

The second argument is an options object. A default is used when no saved value exists; it is not a validation rule for old data. Check stored values before treating them as a restricted theme name.

```tsx
const [theme, setTheme] = useLocalStorageState("theme", { defaultValue: "dark" });
```

## Connect a Bounded Quantity Control

This example keeps behavior local and uses the same Kamod buttons as the rest of the interface. The disabled states explain the limits, and reset returns to the starting quantity. Render it twice to see that each instance owns its own count.

File: src/components/Quantity.tsx

```tsx
import { useCounter } from "@kamod-ch/hooks";
import { Button } from "@kamod-ch/ui";

export function Quantity() {
  const [count, { inc, dec, reset }] = useCounter(1, { min: 1, max: 5 });
  return (
    <div role="group" aria-label="Quantity" class="flex flex-wrap items-center gap-2">
      <Button variant="outline" disabled={count === 1} onClick={() => dec()}>Remove one</Button>
      <output aria-live="polite">{count}</output>
      <Button variant="outline" disabled={count === 5} onClick={() => inc()}>Add one</Button>
      <Button variant="ghost" onClick={reset}>Reset</Button>
    </div>
  );
}
```

Try the minimum, maximum and reset paths with a keyboard. When this becomes a cart control, send the intended quantity through your application boundary and handle server rejection separately; a local count is not proof of available stock.

## Ownership and environment

Start with the smallest owner that needs the behavior. Move a hook into a custom hook when several components need the same logic, not simply because a file is long. Sharing the function does not share its state: separate calls still represent separate instances. Lift ownership only when the product requires synchronized values.

Browser hooks and server rendering have different timing. Keep direct access to window, document and storage out of server render paths. Prefer a stable initial render and apply browser-only information after mount. For asynchronous interactions, decide what the user sees while a request is pending and when a later request replaces it.

A reusable interaction should preserve its behavior when the surrounding markup changes. Keep hook ownership stable while adjusting buttons, labels and layout.

## Troubleshooting

### The value resets unexpectedly

Check whether a changing key or a conditional parent unmounts the component. Local state belongs to that mounted instance; moving the visual control can change its lifetime.

### The saved preference has an unexpected type

Inspect old storage values and your serializer. TypeScript describes current code, not historical browser data. Test fresh storage and an older value before deciding on a migration.

### An interaction repeats or finishes late

Look for listeners, timers or requests created outside the hook's lifecycle. Verify cleanup when navigating away and rapid repeated input; do not hide the issue by suppressing all errors.

## Resources

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

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

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

## Attribution

Kamod Hooks is inspired by ahooks and adapts those patterns for Preact. Consult the package's LICENSE and NOTICE when redistributing source; compatibility and behavior should be checked against Kamod's own documentation.

[Ahooks by Alibaba](https://github.com/alibaba/hooks)

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

## Companion packages

A good hook solves one behavior. Add a companion when your feature needs a longer lifetime, clearer transitions or a wider audience—not just another abstraction.

### Signals — Let a preference travel

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

A display preference can outgrow the component that first introduced it. Compare persistedSignal with useLocalStorageState when several screens need the same value; choose one owner instead of maintaining two writable copies.

### State — Give a workflow a vocabulary

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

Keep small interactions in hooks, then use named actions for a workflow shared across screens. A draft editor is a useful example: the store owns the draft, while the component owns whether its help panel is open.

### i18n — Make the feedback speak

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

Counters, loading messages and confirmation labels need complete translated sentences. Keep numeric values in the hook and format the message at the view boundary, so language changes do not reset the underlying interaction.

## One interaction, properly finished.

Put the bounded quantity example into a real field: label the value, explain its limits and show what happens at the minimum and maximum. A working interaction is a better next milestone than a larger hook collection.

[Explore Input controls](https://ui.kamod.ch/docs/input/installation)

Try keyboard input, a repeated action and navigating away while work is pending.

[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/hooks, 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.

Keep the Source Close

Look it up, then build

Kamod Hooks is inspired by ahooks and adapts those patterns for Preact. Consult the package's LICENSE and NOTICE when redistributing source; compatibility and behavior should be checked against Kamod's own documentation. See Ahooks by Alibaba for the original project.

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

One Interaction, Properly Finished.

Put the bounded quantity example into a real field: label the value, explain its limits and show what happens at the minimum and maximum. A working interaction is a better next milestone than a larger hook collection.

Try keyboard input, a repeated action and navigating away while work is pending.

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.