@funtools/store
v2.0.5
Published
Lightweight external store for React, React Native and Next.js
Readme
@funtools/store
Lightweight external store for React, React Native and Next.js
A small, zero-dependency runtime for shared state in React apps. It provides:
- Auto-generated handlers for arrays, objects and booleans
createStorefor global stores andcreateStoreProviderfor scoped stores- A minimal API surface with typed handlers and selector-based subscriptions
Quick install
Install the published package or use the repo build for local development:
npm install @funtools/storeTo develop locally, build the package output (dist/):
npm run buildExports
createStore(options)— Create a global store (returns{ useStore, useHandlers, handlers }).createStoreProvider(options)— Returns{ Provider, useStore, useHandlers }for scoped stores (React context).
These are exported from the package root.
Core concepts
states: the initial state object you pass when creating the store.syncHandlers: optional custom synchronous handlers.asyncHandlers: optional custom asynchronous handlers (returning Promises).useStore(selector): React hook that subscribes to a selected snapshot of state.useHandlers(): returns the combined handlers object (auto-generated + custom).
Handlers for individual state keys are also exposed on the root handlers object returned by createStore.
Auto-generated state handlers
For each key in states the library generates a handler object under handlers.<key> with the following methods:
get()— returns the current value for this key.set(action)— set a value or pass a function(prev) => next(usesrunAction).reset()— restore the initial default value.
Additional helpers are generated based on the value type:
- Arrays:
push,pop,shift,unShift,update(index, action),remove(index) - Booleans:
toggle() - Objects:
update(path, action)(dot-paths supported),updateMany(partial)
Custom syncHandlers and asyncHandlers are wrapped so they receive { states, handlers } as the first argument and trigger subscribers after execution. The combined handlers object is frozen to help prevent accidental mutation.
React usage examples
Create a simple store:
import { createStore } from "@funtools/store";
const counterStore = createStore({
states: { count: 0 },
syncHandlers: {
increment: ({ states }) => { states.count += 1; }
},
asyncHandlers: {
fetchAndSet: async ({ states }, url: string) => {
const r = await fetch(url);
const data = await r.json();
states.count = data.value;
}
}
});
function Counter() {
const count = counterStore.useStore(s => s.count);
const handlers = counterStore.useHandlers();
return (
<div>
<div>{count}</div>
<button onClick={() => handlers.increment()}>+1</button>
<button onClick={() => handlers.count.set((v) => v + 5)}>+5</button>
<button onClick={() => handlers.count.reset()}>reset</button>
</div>
);
}Provider (scoped store) usage:
import { createStoreProvider } from "@funtools/store";
const { Provider, useStore, useHandlers } = createStoreProvider({
states: { theme: 'light' }
});
function App() {
return (
<Provider>
<Toolbar />
</Provider>
);
}
function Toolbar() {
const theme = useStore(s => s.theme);
const handlers = useHandlers();
return (
<button onClick={() => handlers.theme.set(theme === 'light' ? 'dark' : 'light')}>
Toggle
</button>
);
}Examples for common types
Boolean:
const store = createStore({ states: { isOpen: false } });
const handlers = store.useHandlers();
handlers.isOpen.toggle();
handlers.isOpen.set(true);
handlers.isOpen.reset();Array:
const store = createStore({ states: { fruits: ['apple'] } });
const handlers = store.useHandlers();
handlers.fruits.push('orange');
handlers.fruits.update(0, (v) => v.toUpperCase());
handlers.fruits.remove(1);
handlers.fruits.set(['kiwi']);
handlers.fruits.reset();Object:
const store = createStore({ states: { user: { name: 'John' } } });
const handlers = store.useHandlers();
handlers.user.update('name', 'Jane');
handlers.user.update('settings.theme', 'dark');
handlers.user.updateMany({ email: '[email protected]' });
handlers.user.reset();Note: each per-key handler also exposes get() to read the current value imperatively where useful.
Custom handlers
Sync handlers example:
const store = createStore({
states: { count: 0, firstName: 'John', lastName: 'Doe' },
syncHandlers: {
increment: (ctx) => { ctx.states.count += 1; },
incrementBy: (ctx, amount: number) => { ctx.states.count += amount; },
setFullName: (ctx, first: string, last: string) => {
ctx.states.firstName = first;
ctx.states.lastName = last;
}
}
});Async handlers example:
const store = createStore({
states: { user: null, loading: false, error: null },
asyncHandlers: {
fetchUser: async (ctx, userId: string) => {
ctx.states.loading = true;
ctx.states.error = null;
try {
const r = await fetch(`/api/users/${userId}`);
ctx.states.user = await r.json();
} catch (e) {
ctx.states.error = 'Failed to fetch user';
} finally {
ctx.states.loading = false;
}
}
}
});Performance notes
useStore(selector)usesuseSyncExternalStoreand the library caches snapshots per-hook instance. Components re-render only when the selected snapshot changes (shallow comparison).- The handlers object is frozen; custom handlers are wrapped to call subscribers after they run.
Types (TypeScript)
Types are inferred from the states and from custom handlers. The main types live under src/core/configStore/types.ts.
Developing locally
src/— source files (entry issrc/index.ts).app.test/— small Vite React app that demonstrates library usage.
Commands:
# build library
npm run build
# development watch
npm run dev
# run example app
cd app.test
npm install
npm run devTip: app.test depends on the built package. Use the dev:yalc script or publish locally with yalc to test changes without publishing to npm.
Contributing
Open an issue or PR, follow standard GitHub contribution flow. See package.json for build scripts.
License
MIT
Made with ❤️ by @funtools24
