Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-storage-hooks

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-storage-hooks

React hooks for state sync with localStorage

  • 3.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
20K
decreased by-20.47%
Maintainers
1
Weekly downloads
 
Created
Source

React storage hooks

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

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

:sparkles: 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. Expect it to just work.

:zap: Tiny and fast. Less than 1kb gzipped. No external dependencies. Only reads from storage when necessary and always updates application state before writing.

:capital_abcd: Completely typed. Written in TypeScript. Type definitions included.

:muscle: Backed by tests. Full coverage of the whole API.

Install

Since this library provides custom React hooks, you need a working React environment. I recommend the official Create React App.

Add the library to your project with npm:

npm install --save react-storage-hooks

Or with yarn:

yarn add react-storage-hooks

And import the hooks to use them:

import {
  useLocalStorageState,
  useLocalStorageReducer,
  useSessionStorageState,
  useSessionStorageReducer,
} from 'react-storage-hooks';

Usage

Four hooks are included:

  • For localStorage: useLocalStorageState and useLocalStorageReducer.
  • For sessionStorage: useSessionStorageState and useSessionStorageReducer.

They mirror the API of React's built-in useState and useReducer hooks. Please read their docs to learn how to use them, and don't hesitate to file an issue if you happen to find diverging behavior.

The only but important differences are:

  • You need to provide a storage key as an additional first parameter. This is mandatory.
  • The initial state parameter only applies if there's no data in storage for the provided key. Otherwise the storage data will be used. Think of it as a default state.
  • The array returned by the 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.

useLocalStorageState and useSessionStorageState

useState hooks with localStorage or sessionStorage persistence.

const [state, setState, writeError] = useLocalStorageState(key, defaultState?);
const [state, setState, writeError] = useSessionStorageState(key, defaultState?);
Example
import React from 'react';
import { useLocalStorageState } from 'react-storage-hooks';

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

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

useLocalStorageReducer and useSessionStorageReducer

useReducer hooks with localStorage or sessionStorage persistence.

const [state, dispatch, writeError] = useLocalStorageReducer(
  key,
  reducer,
  initializerArg,
  initializer?
);
const [state, dispatch, writeError] = useSessionStorageReducer(
  key,
  reducer,
  initializerArg,
  initializer?
);
Example
import React from 'react';
import { useLocalStorageReducer } from 'react-storage-hooks';

const initialCount = 0;

const reducer = (state, action) => {
  switch (action.type) {
    case 'reset':
      return { count: initialCount };
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

const Counter = () => {
  const [state, dispatch, writeError] = useLocalStorageReducer(
    'counter',
    reducer,
    {
      count: initialCount,
    }
  );

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

Keywords

FAQs

Package last updated on 10 Apr 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc