npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sasha.p/use-persistent-state

v1.0.5

Published

set of hooks and tools that have useState-like semantic but allows to persist state in various storage

Readme

Persistent State Utilities

A tiny, type-safe toolkit for persisting React state to different backends using declarative schemas. Define how each field is serialized/deserialized once, and reuse the same schema with:

  • LocalStorage
  • URL Search Params
  • Custom storages

Full TypeScript inference included.


Features

  • 🔒 Type-safe schemas with DataType<T> (serialize/deserialize per-field)
  • 💾 Multiple backends: localStorage, URL query, or your own
  • ⚛️ React hooks: usePersistentState, useLocalStorageState, useSearchParamsState
  • 🧩 Default values supported per-field
  • 📦 Utility fns for direct read/write without hooks

Installation

npm i @sasha.p/use-persistent-state

Core Concepts

DataType<T, D>

Defines how a single field is persisted:

export type DataType<T, D = null> = {
  serialize(value: NonNullable<T>): string;
  deserialize(serializedValue?: string | null | undefined): T | D;
};
  • T — runtime type you want to work with
  • D — fallback type when there is no value (defaults to null)
  • deserialize should return either a value of T or the fallback D

Creating DataTypes

Use the provided factory helper to build consistent data types with optional defaults:

export const createDataTypeCtr = <T>(
  impl: (options?: { defaultValue?: T }) => DataType<T, any>,
) => {
  /* ... */
};

This yields curried creators like $String, $Number, etc., each supporting:

  • No options → fallback is null
  • { defaultValue } → fallback is that value

Built-in Data Types

  • $String – persists strings
  • $StringArray – persists string arrays
  • $Number – persists numbers
  • $NumberArray – persists number arrays
  • $Boolean – persists booleans

Example with defaults:

const name = $String({ defaultValue: 'John' });
const age = $Number({ defaultValue: 30 });
const tags = $StringArray({ defaultValue: [] });

Schema

Schemas describe the shape of your persistent state:

const schema = {
  name: $String({ defaultValue: 'Guest' }),
  age: $Number(),
  tags: $StringArray({ defaultValue: [] }),
};

This produces a fully typed object when loaded.


React Hooks

usePersistentState

Backend-agnostic hook that powers all others:

const [state, setState] = usePersistentState(schema, {
  get: (key) => storage.getItem(key),
  save: (data) => storage.setItem('myKey', JSON.stringify(data)),
});
  • state → typed object matching schema
  • setState(update) → updates and persists values

useLocalStorageState

Persist state in localStorage:

const schema = {
  theme: $String({ defaultValue: 'light' }),
  count: $Number({ defaultValue: 0 }),
};

const [state, setState] = useLocalStorageState(schema, { key: 'app-settings' });

// Usage
console.log(state.theme); // "light"
setState({ theme: 'dark' });

useSearchParamsState

Persist state in URL query params:

const schema = {
  page: $Number({ defaultValue: 1 }),
  filter: $String(),
};

const [state, setState] = useSearchParamsState(schema);

// Usage
console.log(state.page); // 1 (from ?page=1)
setState({ page: 2 }); // updates URL to ?page=2

Non-hook Utilities

getPersistedValues

Read persisted values directly:

const values = getPersistedValues(schema, { key: 'app-settings' });

persistValues

Write values directly:

persistValues(schema, { theme: 'dark', count: 5 }, { key: 'app-settings' });

Custom Storages

Implement the Storage interface to create your own backend:

export interface Storage<Key = string> {
  get(key: Key): string | null;
  save(data: object): void;
}

Example: sessionStorage adapter:

const sessionStorageAdapter: Storage<string> = {
  get: (key) => sessionStorage.getItem(key),
  save: (data) => sessionStorage.setItem('state', JSON.stringify(data)),
};

Example

const schema = {
  username: $String({ defaultValue: 'Anonymous' }),
  darkMode: $Boolean({ defaultValue: false }),
};

function App() {
  const [state, setState] = useLocalStorageState(schema, { key: 'settings' });

  return (
    <div>
      <p>Hello, {state.username}</p>
      <button onClick={() => setState({ darkMode: !state.darkMode })}>
        Toggle Dark Mode
      </button>
    </div>
  );
}

License

MIT © Your Name