⚡Kosha: A Modern, Lightweight, and High-Performance State Management Library for React
Kosha is a production-ready, minimalistic global state management solution for modern React applications. At just ~450 bytes minzipped, it's optimized for performance-critical applications, full React 18+ support, and clean developer ergonomics.
Live demo: https://kosha-six.vercel.app
- 🚀 Features
- 📦 Installation
- 🧑💻 Usage
- 🧰 Immer Middleware
- ⚖️ Zustand Comparison
- 📁 Examples
- ❓ FAQ
- 🚧 Known Limitations
- 🤝 Contributing
- 🧪 Testing and Mocking
- 🧠 Internals & Caveats
- 📜 License
-
Ultra-Lightweight
- Minzipped size: ~420–460 bytes, ideal for bundle-sensitive projects.
-
Optimized by Default: Zero Unnecessary Re-renders
- Uses
useSyncExternalStore
for subscription handling and memoization. - No need to manually optimize with
shallow
equality — Kosha usesJSON.stringify
internally to compare selector outputs.
- Uses
-
Partial State Updates
-
Update only what you need without spreading old state:
set({ count }); set(state => ({ count: state.count + 1 }));
-
-
Concurrent Rendering Ready
- Fully supports React 18+ and concurrent features.
-
Flexible Consumption API
-
Consume whole store or optimized slices via selectors.
const count = useKosha(state => state.count); // optimized - re-renders only when count changes const { count, setCount } = useKosha(); // re-renders for every state change
-
-
Middleware Architecture (BYO Middleware)
- Middleware support is built-in. While Kosha doesn’t yet include a plugin ecosystem like Zustand, you can define and compose custom middlewares easily.
- Includes working persist middleware and immer middleware example out-of-the-box
Install using your preferred package manager:
pnpm add kosha
or
npm install kosha
or
yarn add kosha
import { create } from "kosha";
const useKosha = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
}));
const { count, increment } = useKosha();
This will trigger re-render even when count or increment are not changed but other states [part of the same store] change.
const count = useKosha(state => state.count);
const increment = useKosha(state => state.increment);
// or use shorthand
const { count, increment } = useKosha(({ count, increment }) => ({ count, increment }));
useKosha.getState().increment();
Kosha detects changes using shallow comparison (JSON.stringify
) between the previous and new result of the selector.
If you mutate state in-place and return the same object reference, listeners will not be triggered, and your UI will not re-render — even though the state has technically changed.
create(set => ({
todos: [],
addTodo: item =>
set(state => {
state.todos.push(item); // ❌ in-place mutation
return state; // same reference!
}),
}));
create(set => ({
todos: [],
addTodo: item =>
set(state => ({
...state,
todos: [...state.todos, item], // ✅ returns a new object
})),
}));
import { produce } from "immer";
create(set => ({
todos: [],
addTodo: item =>
set(
produce(state => {
state.todos.push(item);
}),
),
}));
ℹ️ Kosha does not bundle
immer
by default, but you can use it safely with your own setup or use immer middleware.
Kosha provides a convenient immer middleware to simplify immutable state updates by enabling you to write mutative logic inside the store setter. It internally applies immer
's produce
function automatically.
Example usage:
import { create } from "kosha";
import { immer } from "kosha/middleware";
const useKosha = create(
immer(set => ({
todos: [],
addTodo: (item: string) =>
set(state => {
state.todos.push(item); // safe mutable update with immer middleware
}),
})),
);
This middleware allows you to write concise, mutable-looking update code while keeping the state immutable under the hood.
You can combine immer
middleware with other middlewares like persist
for powerful state management.
For large or modular applications, it's often useful to split your store logic into isolated, reusable slices. Kosha supports this pattern with a simple and intuitive API that lets you compose your global store from smaller, focused units of state and behavior.
- Promote separation of concerns and cleaner organization.
- Encapsulate logic around a specific domain (e.g., auth, UI, settings).
- Enable independent testing and reusability of slices.
- Access the full store inside each slice via
get()
— helpful when cross-slice coordination is needed.
interface CounterSlice {
count: number;
setCount: (count: number) => void;
}
interface ThemeSlice {
theme: string;
setTheme: (theme: string) => void;
}
type StoreType = CounterSlice & ThemeSlice;
const createCounterSlice: SliceCreator<StoreType, CounterSlice> = set => ({
count: 0,
setCount: count => set({ count }),
});
const createThemeSlice: SliceCreator<StoreType, ThemeSlice> = set => ({
theme: "light",
setTheme: theme => set({ theme }),
});
const useStore = create<StoreType>((...a) => ({
...createCounterSlice(...a),
...createThemeSlice(...a),
}));
- Each slice gets access to
set()
andget()
functions. - Kosha allows full-store access within any slice, offering more flexibility than Zustand’s default slice typings, where type constraints may prevent access to the full state.
- You can still strongly type your slices using generics — though we're continuing to improve TypeScript ergonomics for advanced use cases.
Feature / Concern | Kosha | Zustand |
---|---|---|
Slice Access to Store | Full access to entire store via get() |
Often restricted to own slice unless manually cast or configured |
DX with TypeScript | More transparent | Auto inferred slice typing, but can obscure full-store access |
Slice Reusability | Easily extractable and composable | Extractable, but full-store interop requires extra typing |
Cross-Slice Communication | Direct via get() |
Indirect or requires casting |
Feature | Kosha | Zustand |
---|---|---|
Size (minzipped) | ~450 bytes | ~0.6–2.5kB+ (depending on usage) |
Optimized Selectors | ✅ Built-in via stringify | |
Partial Updates | ✅ | ✅ |
Middleware Support | ✅ (custom) | ✅ (rich plugin ecosystem) |
Devtools | ❌ (custom only) | ✅ |
Plugin Ecosystem | 🚧 (in development) | ✅ |
Kosha is perfect for apps that prioritize bundle size, simplicity, and predictable updates without the need for extensive tooling.
Explore the examples/
directory for working codebases, including component and selector examples.
Yes. Kosha is small, stable, and well-tested.
Absolutely. Define async
functions inside the store:
const useStore = create(set => ({
fetchUser: async () => {
const user = await fetch("/api/user").then(res => res.json());
set({ user });
},
}));
Yes. Middleware support is built-in. A working persist middleware is included. You can easily build your own or extend with logging, devtools, etc.
You might be mutating the existing state object in-place instead of returning a new one. Kosha relies on reference comparison (JSON.stringify
) to detect changes. Always return a new object, or use libraries like immer or the immer middleware from kosha/middleware
to handle immutable updates safely.
While Date
serializes fine, avoid storing Set
or Map
directly in global state, since Kosha uses JSON.stringify
to diff selector outputs. Use arrays or plain objects instead for best results.
No — in Kosha, you’re comparing outputs of the same selector function across renders. Since the order of keys in JavaScript objects is preserved in deterministic function outputs, JSON.stringify remains stable and reliable in this context.
Kosha is intentionally minimal by design — built to offer just what most React apps need, without bloat. That comes with a few tradeoffs:
Kosha uses JSON.stringify
internally to compare selector outputs for change detection. This works extremely well for the majority of cases — even with moderately large or deeply nested selectors.
However, there are a few caveats:
- Avoid non-serializable values in selectors like
Set
,Map
,WeakMap
, or circular objects. - Very large selector outputs may incur performance costs during diffing.
To clarify: ✅ It’s perfectly fine to have a large store or global state.
⚠️ What matters is the output of your selector. If you’re selecting a large slice likestate => ({ a: state.a, ..., z: state.z })
, it’s more efficient to either:
- Access the store directly without a selector (
useKosha()
), or- Extract only the minimal fields you actually need.
Kosha includes full support for custom middleware and already ships with a working persist middleware. However:
- Built-in plugins like
devtools
are not yet included. - A community-driven plugin ecosystem is still in its early stages.
That said, the underlying architecture is solid and middleware-ready — you're free to build and compose your own middleware as needed.
We welcome contributions!
- 💬 Start a discussion
- 🐛 Report bugs on the issue tracker
- 🧪 Submit PRs to improve or extend Kosha
Got an idea for a middleware plugin or improvement? We'd love to collaborate.
Here’s a polished and clarified version of your 🧪 Testing and Mocking section, optimized for developer clarity, best SEO, and practical DX. It clearly introduces the utilities, explains the pattern, and emphasizes what's already available via utils/test
.
Kosha provides built-in support for test-friendly patterns that allow you to inject and reset store state during testing.
For advanced test isolation, Kosha allows you to create test stores that can be reset to their initial state after each test.
We recommend using the utilities exported from utils/test
:
import { create, resetAllStores } from "kosha/utils/test";
Here’s what they do:
// utils/test.ts
import { create as actualCreate, BaseType, StoreCreator } from "kosha";
export const storeResetFns = new Set<() => void>();
export const create = <T extends BaseType>(creator: StoreCreator<T>) => {
const useStore = actualCreate(creator);
const initial = useStore.getState();
storeResetFns.add(() => useStore.setState(initial!, true));
return useStore;
};
export const resetAllStores = () => storeResetFns.forEach(fn => fn());
This utility enables the following DX pattern in your test setup:
import { act } from "react-dom/test-utils";
import { afterEach } from "vitest"; // or jest
import { resetAllStores } from "kosha/utils/test";
afterEach(() => {
act(() => resetAllStores());
});
- ✅ Stable Testing: Reset store state between tests to prevent bleed-through.
- ✅ Mock with Confidence: Easily inject specific state values for targeted testing.
- ✅ No Manual Boilerplate: Reuse
create()
fromutils/test
for clean and repeatable test setups.
This approach ensures clean state isolation and minimal friction when writing tests for components relying on global state. It's also ideal for mocking feature flags, user sessions, themes, etc.
Kosha compares previous and next selector outputs using JSON.stringify
to prevent unnecessary re-renders. This approach has several benefits:
- It's fast and works for most serializable primitives and plain objects.
- It ensures deep comparison out-of-the-box without manual equality functions.
This is a common concern, but not an issue in Kosha:
Kosha always compares results of the same selector function, so the key order is preserved unless your selector behaves non-deterministically (e.g., relies on
Object.keys()
or mutation). As long as your selector returns a consistent structure,JSON.stringify
comparison will be reliable.
Kosha is licensed under the MPL-2.0 license.
Explore my courses or support development.
Built with 💖 by Mayank Kumar Chaudhari