ilokesto

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);

If the second form is your real use case, read Existing Store next. That page explains when create(store) is the right boundary and what does not change when you bind React onto an already-owned 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 dispatch function that accepts an action: dispatch({ type: 'increment' }).

Important Notes

  • No Initializer Functions: create does not support Zustand-style initializer functions like (set, get) => ({ ... }).
  • Selector Subscriptions: The hook internally uses useSyncExternalStore to subscribe to the store.
  • SSR Support: Supports SSR by using store.getInitialState() for the server snapshot.

Where to go next

  • Read Selectors if you want the subscription and memoization model in detail.
  • Read Accessors if you plan to move actions outside components.
  • Read Existing Store if your app already owns a vanilla Store and only needs the React hook layer.

On this page