ilokesto

Quick start

This guide builds a tiny cart store with plain TypeScript. The important loop is: create the store, read the current value, subscribe to changes, replace state with setState(), then unsubscribe when the listener is no longer needed.

1. Create a typed store

import { Store } from "@ilokesto/store";

type CartItem = {
  id: string;
  title: string;
  quantity: number;
};

type CartState = {
  items: CartItem[];
};

const cartStore = new Store<CartState>({
  items: [],
});

The constructor stores the exact initial value you pass. getInitialState() later returns that original value; it is not a reset method.

2. Read the latest state

const cart = cartStore.getState();
console.log(cart.items);

getState() returns the current value synchronously. Treat object and array state as immutable even though TypeScript cannot deeply freeze the value at runtime.

3. Subscribe and clean up

const unsubscribe = cartStore.subscribe(() => {
  const nextCart = cartStore.getState();
  console.table(nextCart.items);
});

A listener receives no arguments. Read the latest state inside the listener. Keep the returned unsubscribe function and call it when the owner of the listener unmounts, disconnects, or finishes its work.

4. Replace state with setState()

function addItem(item: CartItem): void {
  cartStore.setState((prev) => ({
    items: [...prev.items, item],
  }));
}

function increaseQuantity(id: string): void {
  cartStore.setState((prev) => ({
    items: prev.items.map((item) =>
      item.id === id ? { ...item, quantity: item.quantity + 1 } : item
    ),
  }));
}

function clearCart(): void {
  cartStore.setState({ items: [] });
}

setState() does not shallow merge or deep merge. If your state is an object, return the full next object shape you want to keep.

5. Run the flow

addItem({ id: "keyboard", title: "Keyboard", quantity: 1 });
increaseQuantity("keyboard");
clearCart();

unsubscribe();

After unsubscribe() runs, later setState() calls no longer trigger that listener.

Next steps

Read Core concepts for the behavioral contract, then use the reference pages when you need exact API details.

On this page