JSPM

tiny-persistent-store

0.1.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 7
  • Score
    100M100P100Q72388F
  • License MIT

A tiny React external store with optional localStorage persistence.

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-store

Why

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 | nulllocalStorage key. Pass null to disable persistence.
  • initialValue: T — the initial value for the store.

Returns:

  • getSnapshot() — returns the current value for React's external store API
  • get() — returns the current value manually
  • set(value) — replaces the current value
  • update(fn) — updates the value based on the current value
  • clear() — resets to initialValue and removes the persisted value
  • subscribe(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