# react-persistent-state-hook

> `React.useState` + BrowserStorage API for persistence

Latest version **0.7.2** (published 2023-12-07) · MIT license · 0 weekly downloads

## Install

```sh
npm install react-persistent-state-hook
pnpm add react-persistent-state-hook
yarn add react-persistent-state-hook
bun add react-persistent-state-hook
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.7.2 |
| Published | 2023-12-07 |
| First published | 2023-09-08 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >= 16 |
| Dependencies | 1 |
| Unpacked size | 22.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | yes |
| GitHub stars | 0 |
| Author | Denis Kabana |
| Maintainers | deniskabana |
| Keywords | react, state, state-management, react-hooks |

## Links

- npm: https://www.npmjs.com/package/react-persistent-state-hook
- Repository: https://github.com/deniskabana/react-persistent-state-hook
- Homepage: https://github.com/deniskabana/react-persistent-state-hook#readme
- Issues: https://github.com/deniskabana/react-persistent-state-hook/issues
- npm.io page: https://npm.io/package/react-persistent-state-hook

## Dependencies (1)

- [react](https://npm.io/package/react.md) 18.2.0

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 0.7.2 (latest) — 2023-12-07
- 0.7.1 — 2023-12-07
- 0.7.0 — 2023-11-28
- 0.14.0 — 2023-09-11
- 0.13.0 — 2023-09-11
- 0.12.2 — 2023-09-11
- 0.12.1 — 2023-09-11
- 0.12.0 — 2023-09-11
- 0.10.1 — 2023-09-09
- 0.9.10 — 2023-09-09
- 0.9.9 — 2023-09-09
- 0.9.8 — 2023-09-09
- 0.9.7 — 2023-09-09
- 0.9.6 — 2023-09-09
- 0.9.5 — 2023-09-09
- … 4 more at https://npm.io/package/react-persistent-state-hook/versions

## README

<div align="center">

# react-persistent-state-hook

`usePersistentState(value, storageKey, options): [value, setValue, purgeValue]`

</div>

<div align="center">

[![Build status](https://img.shields.io/github/actions/workflow/status/deniskabana/react-persistent-state-hook/pr-and-main-tests.yml?branch=main&style=for-the-badge)](/actions/workflows/pr-and-main-tests.yml)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/react-persistent-state-hook?style=for-the-badge)](https://bundlephobia.com/package/react-persistent-state-hook?style=for-the-badge)
[![License](https://img.shields.io/github/license/deniskabana/react-persistent-state-hook?style=for-the-badge)](./LICENSE)
[![Version](https://img.shields.io/npm/v/react-persistent-state-hook?style=for-the-badge)](https://www.npmjs.com/package/react-persistent-state-hook)
[![status](https://img.shields.io/badge/status-production_ready-green?style=for-the-badge)](https://www.npmjs.com/package/react-persistent-state-hook)

💡🧠 A React `useState()` replacement with built-in persistence with [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API). First-class TypeScript support 💪

</div>

```bash
yarn add react-persistent-state-hook # or npm, pnpm, bun, etc.
```

```typescript
// It works just like magic 🌟
const [name, setName] = usePersistentState("John", "user-name")

// For more safety, provide a UNIQUE storageKey (strongly recommended 💪)
const [name, setName] = usePersistentState("Billy", "ui/userAuth/name")

// For more versatility, use ENUMs as keys
const [name, setName] = usePersistentState("Tim", StorageKeys.USER_NAME)
```

---

**Table of contents:**

1. [Key Features](#key-features)
2. [Usage](#usage)
3. [Options API](#options-api)
4. [Roadmap](#roadmap)
5. [Contributing](#contributing)

---

### Key Features

**`usePersistentState` adds persistence to `React.useState` method:**

1. 🐣 **Plug'n'play with Minimal Configuration**:

   A simple replacement for `React.useState` hook - provide a unique key and you're good to go!

2. 🧠 **Data Persistence**:

   Store state values in `localStorage` or `sessionStorage`. Until version 2, we only support Web Storage API, but more are coming.

3. ♻️ **Platform-Agnostic**:

   `usePersistentState` gracefully handles scenarios where Web Storage is not available, behaving exactly like `React.useState`.

4. 📭 **No Dependencies**:

   Keep your project light - no dependencies and a single peer dependency (`react >= 16.8`).

5. 🧑‍💻 **First-class TypeScript Support**:

   Fully typed with TypeScript! 🎉

6. 🚧 **Roadmap for Continuous Improvement**:

   - The roadmap outlines upcoming features and enhancements, ensuring your state management needs are met.

7. 📚 **Documentation and Tutorials**:

   Straight-forward readme with examples and comprehensive JSDoc annotations for the hook and its options.

RPSH is committed to delivering a minimal and flexible solution for state management and persistence in React applications. Join me on this journey by contributing! 🚀

---

### Usage

Start by importing the hook:

```typescript
import { usePersistentState } from "react-persistent-state-hook"
```

#### Basic usage

```typescript
// Replace React.useState without breaking functionality - uses `localStorage`
const [count, setCount] = usePersistentState(0, "count")
const [count, setCount] = usePersistentState(() => 0, "count")

// Easy switching between local and session storages
const [count, setCount] = usePersistentState(0, "unique-key", "local")
const [count, setCount] = usePersistentState(0, "unique-key", "session")

// Configurable with options API
const [count, setCount] = usePersistentState(0, "unique-key", { verbose: true, persistent: false })
```

> 💡 Possible state management replacement (like context or Redux) with zero configuration in situations where data loss is acceptable (like UI preferences). ☝️

```typescript
// You can use your own prefixes to group related keys and prevent conflicts
const [count, setCount] = usePersistentState(0, "count", { prefix: "ui/homepage" })
```

#### Advanced usage

💡 You can create a custom `usePersistentState` hook with default options easily to share or persist configuration values across your application or different contexts:

```typescript
import { createPersistentStateHook } from "react-persistent-state-hook"

// Create your own hook with defaults
export const useMyPersistentState = createPersistentStateHook({
  storageType: "session",
  prefix: "homepage/pagination",
})

// Usage - you can still override default options
const [page, setPage] = useMyPersistentState(1, "page")
```

---

### Options API

The Options API in `react-persistent-state-hook` allows you to tweak the behavior of the hook. More configuration options are coming soon in minor releases.

Breaking changes in the Options API or elsewhere in `react-persistent-state-hook` are only released in major versions 🤞

```typescript
type Options = {
  /** Print all warnings and errors in console. Overrides `silent` option.
   *  @default false */
  verbose: boolean

  /** The type of Web Storage API to use (either "session" or "local").
   *  @default "local" */
  storageType: StorageType

  /** Allow programatically enabling and disabling persistence in-place.
   *  @default true */
  persistent: boolean

  /** Allow the use of custom key prefix - group contexts or invalidate state version.
   *  @default "[rpsh]" */
  prefix: string
}
```

---

### Roadmap

#### Current Plans (`v1.0.0` Release):

- **Resolution Strategies ?**
  - Add option to always override with new value, prefer stored value, or use stored if new value is `undefined` (default)
- **1.0.0 Release 🎉**
  - Freeze the `main` branch and move development to `dev-v1.x` branches, that eventually get merged into `main` as PRs. We need to act responsible 👨‍🏫

#### Planned Improvements

- **More Storage Types**
  - Add support for `IndexedDB`, `AsyncStorage` (React Native), URL params, cookies, etc.
- **Even Smaller Footprint**
  - Reduce bundle size as much as possible
- **Custom Serialization and Deserialization Methods**
  - Add the ability to configure your own serialization and deserialization functions instead of relying on `JSON.stringify` and `JSON.parse` - for example to support `Date` and custom objects
- **Open-source Friendliness**
  - Add a `CONTRIBUTING.md` file to make it easier for contributors to get started, link to it from `README.md`
  - Provide a solid tutorial for contributors, set up PR template, issue template, etc.
- **Storage Adapters API**
  - Say goodbye to Web Storage API as a core feature and say hello to storage adapters API. More flexibility, more possibilities! 🔄
  - Implement Web Storage and in-memory storage as exported storage adapter functions / objects

---

### Contributing

[Start a new issue](https://github.com/deniskabana/react-persistent-state-hook/issues) whenever you have any questions, problems or suggestions! Or feel free to [open a pull request](https://github.com/deniskabana/react-persistent-state-hook/pulls) if you want to contribute. To increase the speed of getting your PR merged, please open an issue first to discuss your idea.

More info coming soon.

---
_Source: https://npm.io/package/react-persistent-state-hook · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
