mtzs-lab-state
v1.0.7
Published
A tiny React state management package for the MTZS ecosystem.
Downloads
824
Maintainers
Readme
mtzs-lab-state
Lightweight React state management for the MTZS ecosystem. Two complementary APIs:
create()— Zustand-style. State + actions bundled. Returns a hook directly.createStore()+useStore()— explicit store + selector hook. Backwards-compatible.
Installation
pnpm add mtzs-lab-statenpm install mtzs-lab-statePeer dependency:
react ^19Quick Start — create() (Recommended)
import { create } from "mtzs-lab-state";
export const useCounter = create<{
count: number;
inc: () => void;
reset: () => void;
}>((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 })
}));Use in a component:
import { useCounter } from "./stores/counter";
export function Counter() {
const count = useCounter((s) => s.count);
const inc = useCounter((s) => s.inc);
return <button onClick={inc}>Count: {count}</button>;
}Outside React (vanilla):
useCounter.getState(); // current state
useCounter.setState({ count: 5 }); // shallow merge
useCounter.setState(
{ count: 10, inc: () => {}, reset: () => {} },
true // replace (no merge)
);
useCounter.subscribe((state, prevState) => {
console.log("changed:", prevState, "->", state);
});Quick Start — createStore() (Classic)
import { createStore } from "mtzs-lab-state";
export const counterStore = createStore({ count: 0 });import { useStore } from "mtzs-lab-state";
import { counterStore } from "./counterStore";
export function Counter() {
const count = useStore(counterStore, (s) => s.count);
return (
<button onClick={() => counterStore.setState((s) => ({ count: s.count + 1 }))}>
Count: {count}
</button>
);
}API
create(initializer)
create<T extends object>(
initializer: (set, get, api) => T
): UseBoundStore<T>Returns a hook that doubles as a store API. Call it with a selector for fine-grained re-renders, or without arguments to get the full state.
createStore(initialState)
createStore<T extends object>(initialState: T): Store<T>Creates a store with getState, setState, subscribe.
useStore(store, selector)
useStore<T, S>(store: Store<T>, selector: (state: T) => S): SReact hook. Re-renders only when the selected slice changes (via Object.is).
Selector Tips
Always select narrowly to minimize re-renders:
// re-renders only when count changes
const count = useCounter((s) => s.count);
// re-renders on every state change
const state = useCounter();Built on useSyncExternalStore — zero tearing under React 18 concurrent rendering.
License
MIT
