Package Exports
- tiny-persistent-store
Readme
tiny-persistent-store
A tiny, type-safe external store for React with optional localStorage
persistence. It uses React's useSyncExternalStore API and has no runtime
dependencies besides React.
Install
npm install tiny-persistent-storeBasic usage
// stores/counterStore.ts
import { createStorageStore } from "tiny-persistent-store";
// Pass a key to persist the value to localStorage.
export const counterStore = createStorageStore("counter", 0);// components/Counter.tsx
import { useStore } from "tiny-persistent-store";
import { counterStore } from "../stores/counterStore";
export function Counter() {
const count = useStore(counterStore);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => counterStore.update((current) => current + 1)}>
Increment
</button>
<button onClick={() => counterStore.clear()}>Reset</button>
</div>
);
}Any component that calls useStore(counterStore) will re-render when the value
changes.
Optional persistence
localStorage persistence is optional. Pass null instead of a storage key to
create an in-memory-only store:
import { createStorageStore } from "tiny-persistent-store";
export const modalStore = createStorageStore(null, false);API
createStorageStore(key, initialValue)
Creates a store.
key: string | null: thelocalStoragekey, ornullto disable persistenceinitialValue: T: the initial value for the store
The returned store provides:
getSnapshot(): returns the current value for React's external store APIget(): returns the current valueset(value): replaces the current valueupdate(updater): updates the value based on the current valueclear(): resets the store and removes its persisted valuesubscribe(listener): subscribes to changes and returns an unsubscribe function
useStore(store)
Subscribes a React component to a store and returns its latest value.
License
Licensed under the MIT License.