Package Exports
- tiny-persistent-store
Readme
tiny-persistent-store
A tiny React external store with optional localStorage persistence.
It is built around a simple idea:
- keep the current value in memory
- notify subscribers when the value changes
- optionally persist the value to
localStorage - connect React components with
useSyncExternalStore
npm install tiny-persistent-storeWhy
localStorage can save data between page refreshes, but it does not notify
React when that data changes.
This package gives you a small external store API for cases where you want a simple global value without setting up a larger state-management solution.
Usage
// stores/counterStore.ts
import { createStorageStore } from "tiny-persistent-store";
// Pass a key to persist 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)}>
+
</button>
<button onClick={() => counterStore.clear()}>Reset</button>
</div>
);
}Any component that calls useStore(counterStore) will re-render when the value
changes.
In-memory only store
Pass null as the key if you do not want persistence:
import { createStorageStore } from "tiny-persistent-store";
export const modalStore = createStorageStore(null, false);API
createStorageStore(key, initialValue)
Creates a store.
key: string | null—localStoragekey. Passnullto disable persistence.initialValue: T— the initial value for the store.
Returns:
getSnapshot()— returns the current value for React's external store APIget()— returns the current value manuallyset(value)— replaces the current valueupdate(fn)— updates the value based on the current valueclear()— resets toinitialValueand removes the persisted valuesubscribe(listener)— subscribes to changes and returns an unsubscribe function
useStore(store)
React hook that subscribes a component to a store and returns the latest value.
Notes
This is not intended to replace Redux or other full state-management libraries in large applications. It is a small utility for simple global state and for learning how external stores work in React.
License
MIT