All Projects → soyguijarro → React Storage Hooks

soyguijarro / React Storage Hooks

Licence: mit
React hooks for persistent state

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to React Storage Hooks

Vue Ls
💥 Vue plugin for work with local storage, session storage and memory storage from Vue context
Stars: ✭ 468 (+220.55%)
Mutual labels:  storage, localstorage, sessionstorage
ng2-storage
A local and session storage wrapper for angular 2.
Stars: ✭ 14 (-90.41%)
Mutual labels:  storage, localstorage, sessionstorage
Brownies
🍫 Tastier cookies, local, session, and db storage in a tiny package. Includes subscribe() events for changes.
Stars: ✭ 2,386 (+1534.25%)
Mutual labels:  storage, localstorage, sessionstorage
Angular Locker
🗄️ A simple & configurable abstraction for local/session storage in angular js projects
Stars: ✭ 318 (+117.81%)
Mutual labels:  storage, localstorage, sessionstorage
vue-web-storage
Vue.js plugin for local storage and session storage (1.8 kb min+gz) 💾
Stars: ✭ 85 (-41.78%)
Mutual labels:  storage, localstorage, sessionstorage
h5webstorage
Web Storage for Angular 2
Stars: ✭ 38 (-73.97%)
Mutual labels:  storage, localstorage, sessionstorage
Proxy Storage
Provides an adapter for storage mechanisms (cookies, localStorage, sessionStorage, memoryStorage) and implements the Web Storage interface
Stars: ✭ 10 (-93.15%)
Mutual labels:  storage, localstorage, sessionstorage
Store
A better way to use localStorage and sessionStorage
Stars: ✭ 1,646 (+1027.4%)
Mutual labels:  storage, localstorage, sessionstorage
persistence
💾 Persistence provides a pretty easy API to handle Storage's implementations.
Stars: ✭ 18 (-87.67%)
Mutual labels:  storage, localstorage, sessionstorage
stoor
Storage wrapper with support for namespacing, timeouts and multi get/set and remove.
Stars: ✭ 26 (-82.19%)
Mutual labels:  storage, localstorage, sessionstorage
Immortaldb
🔩 A relentless key-value store for the browser.
Stars: ✭ 2,962 (+1928.77%)
Mutual labels:  storage, localstorage, sessionstorage
Recoil Persist
Package for recoil state manager to persist and rehydrate store
Stars: ✭ 66 (-54.79%)
Mutual labels:  storage, localstorage, sessionstorage
Ng2 Webstorage
Localstorage and sessionstorage manager - Angular service
Stars: ✭ 395 (+170.55%)
Mutual labels:  localstorage, sessionstorage
Localforage
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Stars: ✭ 19,840 (+13489.04%)
Mutual labels:  storage, localstorage
Use Local Storage State
React hook that persists data in local storage
Stars: ✭ 392 (+168.49%)
Mutual labels:  persistent, localstorage
Local Storage
React hook which syncs localStorage[key] with the comp.
Stars: ✭ 402 (+175.34%)
Mutual labels:  hooks, localstorage
Vuex Persistedstate
💾 Persist and rehydrate your Vuex state between page reloads.
Stars: ✭ 5,561 (+3708.9%)
Mutual labels:  storage, localstorage
Storagedb
MongoDB-like API for HTML5 Storage (localStorage and sessionStorage)
Stars: ✭ 16 (-89.04%)
Mutual labels:  localstorage, sessionstorage
Vagrant Persistent Storage
A Vagrant plugin that creates a persistent storage and attaches it to guest machine.
Stars: ✭ 285 (+95.21%)
Mutual labels:  storage, persistent
Web Storage Cache
对localStorage 和sessionStorage 进行了扩展,添加了超时时间,序列化方法
Stars: ✭ 582 (+298.63%)
Mutual labels:  localstorage, sessionstorage

react-storage-hooks

Version Dependencies Dev dependencies Build status Test coverage Bundle size MIT licensed

Custom React hooks for keeping application state in sync with localStorage or sessionStorage.

📖 Familiar API. You already know how to use this library! Replace useState and useReducer hooks with the ones in this library and get persistent state for free.

Fully featured. Automatically stringifies and parses values coming and going to storage, keeps state in sync between tabs by listening to storage events and handles non-straightforward use cases correctly.

⚡️ Tiny and fast. Less than 700 bytes gzipped, enforced with size-limit. No external dependencies. Only reads from storage when necessary and writes to storage after rendering.

🔠 Completely typed. Written in TypeScript. Type definitions included and verified with tsd.

💪 Backed by tests. Full coverage of the API.

Requirements

You need to use version 16.8.0 or greater of React, since that's the first one to include hooks. If you still need to create your application, Create React App is the officially supported way.

Installation

Add the package to your React project:

npm install --save react-storage-hooks

Or with yarn:

yarn add react-storage-hooks

Usage

The useStorageState and useStorageReducer hooks included in this library work like useState and useReducer. The only but important differences are:

  • Two additional mandatory parameters: Storage object (localStorage or sessionStorage) and storage key.
  • 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.
  • The array returned by hooks has an extra last item for write errors. It is initially undefined, and will be updated with Error objects 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.

useStorageState

Example

import React from 'react';
import { useStorageState } from 'react-storage-hooks';

function StateCounter() {
  const [count, setCount, writeError] = useStorageState(
    localStorage,
    'state-counter',
    0
  );

  return (
    <>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      {writeError && (
        <pre>Cannot write to localStorage: {writeError.message}</pre>
      )}
    </>
  );
}

Signature

function useStorageState<S>(
  storage: Storage,
  key: string,
  defaultState?: S | (() => S)
): [S, React.Dispatch<React.SetStateAction<S>>, Error | undefined];

useStorageReducer

Example

import React from 'react';
import { useStorageReducer } from 'react-storage-hooks';

function reducer(state, action) {
  switch (action.type) {
    case 'inc':
      return { count: state.count + 1 };
    case 'dec':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function ReducerCounter() {
  const [state, dispatch, writeError] = useStorageReducer(
    localStorage,
    'reducer-counter',
    reducer,
    { count: 0 }
  );

  return (
    <>
      <p>You clicked {state.count} times</p>
      <button onClick={() => dispatch({ type: 'inc' })}>+</button>
      <button onClick={() => dispatch({ type: 'dec' })}>-</button>
      {writeError && (
        <pre>Cannot write to localStorage: {writeError.message}</pre>
      )}
    </>
  );
}

Signature

function useStorageReducer<S, A>(
  storage: Storage,
  key: string,
  reducer: React.Reducer<S, A>,
  defaultState: S
): [S, React.Dispatch<A>, Error | undefined];

function useStorageReducer<S, A, I>(
  storage: Storage,
  key: string,
  reducer: React.Reducer<S, A>,
  defaultInitialArg: I,
  defaultInit: (defaultInitialArg: I) => S
): [S, React.Dispatch<A>, Error | undefined];

Advanced usage

Alternative storage objects

The storage parameter of the hooks can be any object that implements the getItem, setItem and removeItem methods of the Storage interface. Keep in mind that storage values will be automatically serialized and parsed before and after calling these methods.

interface Storage {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
}

Server-side rendering (SSR)

This library checks for the existence of the window object and even has some tests in a node-like environment. 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:

const dummyStorage = {
  getItem: () => null,
  setItem: () => {},
  removeItem: () => {},
};

The 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.

Convenience custom hook

If 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:

import { useStorageState } from 'react-storage-hooks';

export function useLocalStorageState(...args) {
  return useStorageState(localStorage, ...args);
}

And then use it in your components:

import { useLocalStorageState } from './my-hooks';

function Counter() {
  const [count, setCount] = useLocalStorageState('counter', 0);

  // Rest of the component
}

Development

Install development dependencies:

npm install

To set up the examples:

npm run examples:setup

To start a server with the examples in watch mode (reloads whenever examples or library code change):

npm run examples:watch

Tests

Run tests:

npm test

Run tests in watch mode:

npm run test:watch

See code coverage information:

npm run test:coverage

Publish

Go to the master branch:

git checkout master

Bump the version number:

npm version [major | minor | patch]

Run the release script:

npm run release

All code quality checks will run, the tagged commit generated by npm version will be pushed and Travis CI will publish the new package version to the npm registry.

License

This library is MIT licensed.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].