Skip to main content

Usage guide

Here you'll learn how to use the library in different contexts within your application. The API is designed to be minimalist, yet powerful.

Basic example

import { create } from "@bentoo/state-man";

const useCounter = create(0);

function Counter() {
const { state, setState } = useCounter();
return (
<button onClick={() => setState(state + 1)}>
Counter: {state}
</button>
);
}

Notice there's no context, provider, reducer, or middleware. Just a hook.

Shared state

Create the store and use it wherever you need.

store/user.ts
import { create } from "@bentoo/state-man";

export const useUser = create({ name: "Ada", email: "" });
components/Header.tsx
import { useUser } from "../store/user";

function Header() {
const { state } = useUser();
return <h2>Hello, {state.name}!</h2>;
}
components/Form.tsx
import { useUser } from "../store/user";

function Form() {
const { setState } = useUser();
return (
<input
placeholder="Name"
onChange={(e) => setState({ name: e.target.value })}
/>
);
}

The two components above share the same state — no need for the Context API.

Safe updates with setState(prev => ...)

In asynchronous situations or when multiple updates may happen, use the updater function to ensure you're working with the latest state:

const { setState } = useCounter();

// ✅ safe approach
setState(prev => prev + 1);

This prevents side effects caused by closures or chained events.

Partial updates (shallow merge)

When dealing with objects, you can update just part of the state without overwriting the rest:

setState(prev => ({ ...prev, email: "ada@lovelace.dev" }));

Best practices

  • Prefer setState(prev => ...) when the new value depends on the previous one.
  • Avoid huge stores. Split by domain (e.g., useUser, useCart).
  • Fully typed with TypeScript (with automatic inference).

TL;DR

TaskHow to do it
Create stateconst store = create(initialValue)
Use in componentconst { state, setState } = store();
Direct updatesetState("newValue")
Functional updatesetState(prev => newVersion)

🧠 Tip: If you already know how to use useState, you know 90% of what you need to use @bentoo/state-man — except now, you can share that state across your whole app.