create
The primary API for building stores in @ilokesto/state.
create
create is the main entry point for @ilokesto/state. It defines your state and returns a hook that components use to interact with that state.
Call Signatures
The create function is overloaded to support two primary modes of operation.
State Mode
In state mode, you provide the initial state directly. The returned hook provides a setState function similar to React's useState.
import { create } from '@ilokesto/state';
// 1. With initial state value
const useCounter = create({ count: 0 });
// 2. With an existing Store instance
import { Store } from '@ilokesto/store';
const store = new Store({ count: 0 });
const useCounterFromStore = create(store);Reducer Mode
In reducer mode, you provide a reducer function and an initial state (or store). The returned hook provides a dispatch function.
type State = { count: number };
type Action = { type: 'increment' } | { type: 'decrement' };
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
};
const useCounter = create(reducer, { count: 0 });Hook Behavior
The hook returned by create accepts a selector function.
function Counter() {
// Returns [selectedState, updater]
const [count, setCountOrDispatch] = useCounter(state => state.count);
// ...
}- In State Mode: The second element is the store writer. Even if your selector returns only one field, the writer still accepts the next full state value or an updater over the full state:
setState((prev) => ({ ...prev, count: prev.count + 1 })). - In Reducer Mode: The second element is a
dispatchfunction that accepts an action:dispatch({ type: 'increment' }).
Important Notes
- No Initializer Functions:
createdoes not support Zustand-style initializer functions like(set, get) => ({ ... }). - Selector Subscriptions: The hook internally uses
useSyncExternalStoreto subscribe to the store. - SSR Support: Supports SSR by using
store.getInitialState()for the server snapshot.