{"id":13850333,"url":"https://github.com/soyguijarro/react-storage-hooks","last_synced_at":"2025-05-13T12:56:47.105Z","repository":{"id":33727465,"uuid":"161063444","full_name":"soyguijarro/react-storage-hooks","owner":"soyguijarro","description":"React hooks for persistent state","archived":false,"fork":false,"pushed_at":"2023-01-07T02:38:04.000Z","size":3477,"stargazers_count":166,"open_issues_count":57,"forks_count":18,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-23T04:52:14.722Z","etag":null,"topics":["hooks","localstorage","persistent","react","react-hooks","sessionstorage","storage"],"latest_commit_sha":null,"homepage":"https://npm.im/react-storage-hooks","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/soyguijarro.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-09T17:21:52.000Z","updated_at":"2024-07-02T15:24:13.000Z","dependencies_parsed_at":"2023-01-15T02:15:30.972Z","dependency_job_id":null,"html_url":"https://github.com/soyguijarro/react-storage-hooks","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/soyguijarro%2Freact-storage-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/soyguijarro%2Freact-storage-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/soyguijarro%2Freact-storage-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/soyguijarro%2Freact-storage-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/soyguijarro","download_url":"https://codeload.github.com/soyguijarro/react-storage-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253948346,"owners_count":21988953,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hooks","localstorage","persistent","react","react-hooks","sessionstorage","storage"],"created_at":"2024-08-04T20:01:06.441Z","updated_at":"2025-05-13T12:56:47.076Z","avatar_url":"https://github.com/soyguijarro.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# react-storage-hooks\n\n[![Version](https://img.shields.io/npm/v/react-storage-hooks.svg)](https://www.npmjs.com/package/react-storage-hooks)\n![Dependencies](https://img.shields.io/david/soyguijarro/react-storage-hooks.svg)\n![Dev dependencies](https://img.shields.io/david/dev/soyguijarro/react-storage-hooks.svg)\n[![Build status](https://travis-ci.com/soyguijarro/react-storage-hooks.svg?branch=master)](https://travis-ci.com/soyguijarro/react-storage-hooks)\n[![Test coverage](https://codecov.io/gh/soyguijarro/react-storage-hooks/branch/master/graph/badge.svg)](https://codecov.io/gh/soyguijarro/react-storage-hooks)\n![Bundle size](https://img.shields.io/bundlephobia/minzip/react-storage-hooks.svg)\n[![MIT licensed](https://img.shields.io/github/license/soyguijarro/react-storage-hooks.svg)](https://github.com/soyguijarro/react-storage-hooks/blob/master/LICENSE)\n\nCustom [React hooks](https://reactjs.org/docs/hooks-intro) for keeping application state in sync with `localStorage` or `sessionStorage`.\n\n:book: **Familiar API**. You already know how to use this library! Replace [`useState`](https://reactjs.org/docs/hooks-reference.html#usestate) and [`useReducer`](https://reactjs.org/docs/hooks-reference.html#usereducer) hooks with the ones in this library and get persistent state for free.\n\n:sparkles: **Fully featured**. Automatically stringifies and parses values coming and going to storage, keeps state in sync between tabs by listening to [storage events](https://developer.mozilla.org/docs/Web/API/StorageEvent) and handles non-straightforward use cases correctly.\n\n:zap: **Tiny and fast**. Less than 700 bytes gzipped, enforced with [`size-limit`](https://github.com/ai/size-limit). No external dependencies. Only reads from storage when necessary and writes to storage after rendering.\n\n:capital_abcd: **Completely typed**. Written in TypeScript. Type definitions included and verified with [`tsd`](https://github.com/SamVerschueren/tsd).\n\n:muscle: **Backed by tests**. Full coverage of the API.\n\n## Requirements\n\nYou need to use [version 16.8.0](https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019) or greater of React, since that's the first one to include hooks. If you still need to create your application, [Create React App](https://create-react-app.dev/) is the officially supported way.\n\n## Installation\n\nAdd the package to your React project:\n\n    npm install --save react-storage-hooks\n\nOr with yarn:\n\n    yarn add react-storage-hooks\n\n## Usage\n\nThe `useStorageState` and `useStorageReducer` hooks included in this library work like [`useState`](https://reactjs.org/docs/hooks-reference.html#usestate) and [`useReducer`](https://reactjs.org/docs/hooks-reference.html#usereducer). The only but important differences are:\n\n- Two additional mandatory parameters: [**`Storage` object**](https://developer.mozilla.org/en-US/docs/Web/API/Storage) (`localStorage` or `sessionStorage`) and **storage key**.\n- Initial state parameters only apply if there's no data in storage for the provided key. Otherwise data from storage will be used as initial state. Think about it as **default** or **fallback state**.\n- The array returned by hooks has an extra last item for **write errors**. It is initially `undefined`, and will be updated with [`Error` objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) thrown by `Storage.setItem`. However the hook will keep updating state even if new values fail to be written to storage, to ensure that your application doesn't break.\n\n### `useStorageState`\n\n#### Example\n\n```javascript\nimport React from 'react';\nimport { useStorageState } from 'react-storage-hooks';\n\nfunction StateCounter() {\n  const [count, setCount, writeError] = useStorageState(\n    localStorage,\n    'state-counter',\n    0\n  );\n\n  return (\n    \u003c\u003e\n      \u003cp\u003eYou clicked {count} times\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e setCount(count + 1)}\u003e+\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e setCount(count - 1)}\u003e-\u003c/button\u003e\n      {writeError \u0026\u0026 (\n        \u003cpre\u003eCannot write to localStorage: {writeError.message}\u003c/pre\u003e\n      )}\n    \u003c/\u003e\n  );\n}\n```\n\n#### Signature\n\n```typescript\nfunction useStorageState\u003cS\u003e(\n  storage: Storage,\n  key: string,\n  defaultState?: S | (() =\u003e S)\n): [S, React.Dispatch\u003cReact.SetStateAction\u003cS\u003e\u003e, Error | undefined];\n```\n\n### `useStorageReducer`\n\n#### Example\n\n```javascript\nimport React from 'react';\nimport { useStorageReducer } from 'react-storage-hooks';\n\nfunction reducer(state, action) {\n  switch (action.type) {\n    case 'inc':\n      return { count: state.count + 1 };\n    case 'dec':\n      return { count: state.count - 1 };\n    default:\n      return state;\n  }\n}\n\nfunction ReducerCounter() {\n  const [state, dispatch, writeError] = useStorageReducer(\n    localStorage,\n    'reducer-counter',\n    reducer,\n    { count: 0 }\n  );\n\n  return (\n    \u003c\u003e\n      \u003cp\u003eYou clicked {state.count} times\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: 'inc' })}\u003e+\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: 'dec' })}\u003e-\u003c/button\u003e\n      {writeError \u0026\u0026 (\n        \u003cpre\u003eCannot write to localStorage: {writeError.message}\u003c/pre\u003e\n      )}\n    \u003c/\u003e\n  );\n}\n```\n\n#### Signature\n\n```typescript\nfunction useStorageReducer\u003cS, A\u003e(\n  storage: Storage,\n  key: string,\n  reducer: React.Reducer\u003cS, A\u003e,\n  defaultState: S\n): [S, React.Dispatch\u003cA\u003e, Error | undefined];\n\nfunction useStorageReducer\u003cS, A, I\u003e(\n  storage: Storage,\n  key: string,\n  reducer: React.Reducer\u003cS, A\u003e,\n  defaultInitialArg: I,\n  defaultInit: (defaultInitialArg: I) =\u003e S\n): [S, React.Dispatch\u003cA\u003e, Error | undefined];\n```\n\n## Advanced usage\n\n### Alternative storage objects\n\nThe `storage` parameter of the hooks can be any object that implements the `getItem`, `setItem` and `removeItem` methods of the [`Storage` interface](https://developer.mozilla.org/en-US/docs/Web/API/Storage). Keep in mind that storage values will be automatically [serialized](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and [parsed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) before and after calling these methods.\n\n```typescript\ninterface Storage {\n  getItem(key: string): string | null;\n  setItem(key: string, value: string): void;\n  removeItem(key: string): void;\n}\n```\n\n### Server-side rendering (SSR)\n\nThis library checks for the existence of the `window` object and even has some [tests in a node-like environment](https://jestjs.io/docs/en/configuration#testenvironment-string). However in your server code you will need to provide a storage object to the hooks that works server-side. A simple solution is to use a dummy object like this:\n\n```javascript\nconst dummyStorage = {\n  getItem: () =\u003e null,\n  setItem: () =\u003e {},\n  removeItem: () =\u003e {},\n};\n```\n\nThe important bit here is to have the `getItem` method return `null`, so that the default state parameters of the hooks get applied as initial state.\n\n### Convenience custom hook\n\nIf you're using a few hooks in your application with the same type of storage, it might bother you to have to specify the storage object all the time. To alleviate this, you can write a custom hook like this:\n\n```javascript\nimport { useStorageState } from 'react-storage-hooks';\n\nexport function useLocalStorageState(...args) {\n  return useStorageState(localStorage, ...args);\n}\n```\n\nAnd then use it in your components:\n\n```javascript\nimport { useLocalStorageState } from './my-hooks';\n\nfunction Counter() {\n  const [count, setCount] = useLocalStorageState('counter', 0);\n\n  // Rest of the component\n}\n```\n\n## Development\n\nInstall development dependencies:\n\n    npm install\n\nTo set up the examples:\n\n    npm run examples:setup\n\nTo start a server with the examples in watch mode (reloads whenever examples or library code change):\n\n    npm run examples:watch\n\n### Tests\n\nRun tests:\n\n    npm test\n\nRun tests in watch mode:\n\n    npm run test:watch\n\nSee code coverage information:\n\n    npm run test:coverage\n\n### Publish\n\nGo to the `master` branch:\n\n    git checkout master\n\nBump the version number:\n\n    npm version [major | minor | patch]\n\nRun the release script:\n\n    npm run release\n\nAll code quality checks will run, the tagged commit generated by `npm version` will be pushed and [Travis CI](https://travis-ci.com/github/soyguijarro/react-storage-hooks) will publish the new package version to the npm registry.\n\n## License\n\nThis library is [MIT licensed](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoyguijarro%2Freact-storage-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsoyguijarro%2Freact-storage-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoyguijarro%2Freact-storage-hooks/lists"}