|
1 |
| -# `{{data.name}}` |
| 1 | +# `use-storage-state` |
2 | 2 |
|
3 |
| -> {{data.description}} |
| 3 | +> React hook that you can wire with any [Storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) compatible API like `localStorage`, `sessionStorage`, or a custom one. |
4 | 4 |
|
5 |
| -[](https://bundlephobia.com/result?p={{data.name}}) |
6 |
| -[](https://github.com/astoilkov/{{data.name}}/actions/workflows/main.yml) |
| 5 | +[](https://www.npmjs.com/package/use-storage-state) |
| 6 | +[](https://bundlephobia.com/result?p=use-storage-state) |
| 7 | +[](https://github.com/astoilkov/use-storage-state/actions/workflows/main.yml) |
7 | 8 |
|
8 | 9 | ## Install
|
9 | 10 |
|
10 | 11 | ```bash
|
11 |
| -npm install {{data.name}} |
| 12 | +npm install use-storage-state |
12 | 13 | ```
|
13 | 14 |
|
14 | 15 | ## Why
|
15 | 16 |
|
| 17 | +- SSR support. |
| 18 | +- Works with React 18 concurrent rendering and React 19. |
| 19 | +- Handles the `Window` [`storage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event) event and updates changes across browser tabs, windows, and iframe's. Disable with `storageSync: false`. |
| 20 | +- Aiming for high-quality with [my open-source principles](https://astoilkov.com/my-open-source-principles). |
| 21 | + |
16 | 22 | ## Usage
|
17 | 23 |
|
| 24 | +```typescript |
| 25 | +import useStorageState from 'use-storage-state' |
| 26 | + |
| 27 | +export default function Todos() { |
| 28 | + const [todos, setTodos] = useStorageState('todos', { |
| 29 | + defaultValue: ['buy avocado', 'do 50 push-ups'] |
| 30 | + }) |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +<details> |
| 35 | +<summary>Todo list example + CodeSandbox link</summary> |
| 36 | +<p></p> |
| 37 | + |
| 38 | +You can experiment with the example [here](https://codesandbox.io/s/todos-example-use-storage-state-tzbfhl?file=/src/App.tsx). |
| 39 | + |
| 40 | +```tsx |
| 41 | +import React, { useState } from 'react' |
| 42 | +import useStorageState from 'use-storage-state' |
| 43 | + |
| 44 | +export default function Todos() { |
| 45 | + const [todos, setTodos] = useStorageState('todos', { |
| 46 | + defaultValue: ['buy avocado'] |
| 47 | + }) |
| 48 | + const [query, setQuery] = useState('') |
| 49 | + |
| 50 | + function onClick() { |
| 51 | + setQuery('') |
| 52 | + setTodos([...todos, query]) |
| 53 | + } |
| 54 | + |
| 55 | + return ( |
| 56 | + <> |
| 57 | + <input value={query} onChange={e => setQuery(e.target.value)} /> |
| 58 | + <button onClick={onClick}>Create</button> |
| 59 | + {todos.map(todo => ( |
| 60 | + <div>{todo}</div> |
| 61 | + ))} |
| 62 | + </> |
| 63 | + ) |
| 64 | +} |
| 65 | + |
| 66 | +``` |
| 67 | + |
| 68 | +</details> |
| 69 | + |
| 70 | +<details> |
| 71 | +<summary id="remove-item">Removing the data from <code>localStorage</code> and resetting to the default</summary> |
| 72 | +<p></p> |
| 73 | + |
| 74 | +The `removeItem()` method will reset the value to its default and will remove the key from the `Storage`. It returns to the same state as when the hook was initially created. |
| 75 | + |
| 76 | +```tsx |
| 77 | +import useStorageState from 'use-storage-state' |
| 78 | + |
| 79 | +export default function Todos() { |
| 80 | + const [todos, setTodos, removeItem] = useStorageState('todos', { |
| 81 | + defaultValue: ['buy avocado'] |
| 82 | + }) |
| 83 | + |
| 84 | + function onClick() { |
| 85 | + removeItem() |
| 86 | + } |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +</details> |
| 91 | + |
| 92 | +<details> |
| 93 | +<summary>Why my component renders twice?</summary> |
| 94 | +<p></p> |
| 95 | + |
| 96 | +If you are hydrating your component (for example, if you are using Next.js), your component might re-render twice. This is behavior specific to React and not to this library. It's caused by the `useSyncExternalStore()` hook. There is no workaround. This has been discussed in the issues: https://github.com/astoilkov/use-storage-state/issues/56. |
| 97 | + |
| 98 | +If you want to know if you are currently rendering the server value you can use this helper function: |
| 99 | +```ts |
| 100 | +function useIsServerRender() { |
| 101 | + return useSyncExternalStore(() => { |
| 102 | + return () => {} |
| 103 | + }, () => false, () => true) |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +</details> |
| 108 | + |
18 | 109 | ## API
|
19 | 110 |
|
20 |
| -## Alternatives |
| 111 | +#### `useStorageState(key: string, options?: StorageStateOptions)` |
| 112 | + |
| 113 | +Returns `[value, setValue, removeItem]` when called. The first two values are the same as `useState()`. The third value calls `Storage.removeItem()` and resets the hook to it's default state. |
| 114 | + |
| 115 | +#### `key` |
| 116 | + |
| 117 | +Type: `string` |
| 118 | + |
| 119 | +The key used when calling `storage.setItem(key)` and `storage.getItem(key)`. |
| 120 | + |
| 121 | +⚠️ Be careful with name conflicts as it is possible to access a property which is already in your storage that was created from another place in the codebase or in an old version of the application. |
| 122 | + |
| 123 | +#### `options.defaultValue` |
| 124 | + |
| 125 | +Type: `any` |
| 126 | + |
| 127 | +Default: `undefined` |
| 128 | + |
| 129 | +The default value. You can think of it as the same as `useState(defaultValue)`. |
| 130 | + |
| 131 | +### `options.storage` |
| 132 | + |
| 133 | +Type: [`Storage`](https://developer.mozilla.org/en-US/docs/Web/API/Storage) |
| 134 | + |
| 135 | +Default: `localStorage` (if `localStorage` is disabled in Safari it fallbacks to `sessionStorage`). |
| 136 | + |
| 137 | +You can set `localStorage`, `sessionStorage`, or other any [`Storage`](https://developer.mozilla.org/en-US/docs/Web/API/Storage) compatible class like [`memorystorage`](https://github.com/download/memorystorage). |
| 138 | + |
| 139 | +#### `options.storageSync` |
| 140 | + |
| 141 | +Type: `boolean` |
| 142 | + |
| 143 | +Default: `true` |
| 144 | + |
| 145 | +Setting to `false` doesn't subscribe to the [Window storage event](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event). If you set to `false`, updates won't be synchronized across tabs, windows and iframes. |
| 146 | + |
| 147 | +#### `options.serializer` |
| 148 | + |
| 149 | +Type: `{ stringify, parse }` |
| 150 | + |
| 151 | +Default: `JSON` |
| 152 | + |
| 153 | +JSON does not serialize `Date`, `Regex`, or `BigInt` data. You can pass in [superjson](https://github.com/blitz-js/superjson) or other `JSON`-compatible serialization library for more advanced serialization. |
21 | 154 |
|
22 | 155 | ## Related
|
| 156 | + |
| 157 | +- [`use-local-storage-state`](https://github.com/astoilkov/use-local-storage-state) — Similar to this hook but for `localStorage` only. |
| 158 | +- [`use-session-storage-state`](https://github.com/astoilkov/use-session-storage-state) — Similar to this hook but for `sessionStorage` only. |
| 159 | +- [`local-db-storage`](https://github.com/astoilkov/local-db-storage) — Tiny wrapper around `IndexedDB` that mimics `localStorage` API. |
0 commit comments