Dharma
A simple and lightweight state management solution for JavaScript and TypeScript applications.
Read the full documentation 📄
Basic usage
import { createStore } from "dharma-core";
const store = createStore({
initialState: { count: 0 },
actions: ({ set }) => ({
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}),
});
const { increment, decrement } = store.actions;
// Subscribe to state changes
const unsubscribe = store.subscribe((state) => console.log(state));
// Update the state
increment();
// { count: 1 }
decrement();
// { count: 0 }
unsubscribe();
With React
dharma-react provides React bindings for dharma-core.
Getting started
- Install the packages:
npm install dharma-core dharma-react
# or
pnpm add dharma-core dharma-react
# or
yarn add dharma-core dharma-react
- Create a store:
import { createStore } from "dharma-core";
export const store = createStore({
initialState: { count: 0 },
actions: ({ set }) => ({
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}),
});
export const { increment, decrement } = store.actions;
- Use the store:
import { useStore } from "dharma-react";
import { decrement, increment, store } from "./store";
function Counter() {
const { count } = useStore(store);
return (
<div>
<div>{count}</div>
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
</div>
);
}