JSPM

tiny-persistent-store

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

A tiny React external store with optional localStorage persistence.

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

Basic 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: the localStorage key, or null to disable persistence
  • initialValue: T: the initial value for the store

The returned store provides:

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