New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@bozhkovatanas/react-use-storage

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bozhkovatanas/react-use-storage

Use Local\Session Storage with React hooks

  • 1.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1
Maintainers
1
Weekly downloads
 
Created
Source

@bozhkovatanas/react-use-storage

depends on stable v16.8.1~

Access Local Storage and Session Storage using React hooks.

With support for:

  • Typescript
  • Custom Serializers/Deserializers
  • Local Storage and Session Storage

Project is a fork of react-use-localstorage

How to use it

Basic Hook Usage

import useLocalStorage from '@bozhkovatanas/react-use-storage';
const [item, setItem] = useStorage < string > ('name', 'Initial Value');

Full example

import React from 'react';
import ReactDOM from 'react-dom';
import useLocalStorage from '@bozhkovatanas/react-use-storage';

import './styles.css';

function App() {
  const [item, setItem] = useStorage < string > ('name', 'Initial Value');

  return (
    <div className="App">
      <h1>Set Name to store in Local Storage</h1>
      <div>
        <label>
          Name:{' '}
          <input
            type="text"
            placeholder="Enter your name"
            value={item}
            onChange={(e) => setItem(e.target.value)}
          />
        </label>
      </div>
    </div>
  );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

UseStorage Options

You can configure the storage type and pass custom (de)serializers to useLocalStorage.

function useStorage<T>(
  key: string,
  initialValue: T,
  options?: UseStorageOptions<T>
): [T, Dispatch<T>];

export interface UseStorageOptions<T> {
  serializer?: (input: T) => string;
  deserializer?: (input: string) => T;
  type?: 'session' | 'local'; // Will default to 'local'
}

Option Defaults

If no options are provided - useStorage will default to localStorage and JSON.strinfigy and JSON.parse will be used for serializing.

Custom Serializers/Deserializers Example:

You can add support for storing values as long as you are able to serialize and deserialize them from strings. Basic example for storing Maps in local storage

const mapSerializer = (value) => {
  const serializedMap = JSON.stringify(Object.fromEntries(value));
  return serializedMap;
},
const mapDeserializer = (value) => {
  const deserializedMap = new Map<string, string>(
  Object.entries(JSON.parse(value))
);
  return deserializedMap;
},

const [map, setMap] = useStorage<Map<string, string>>('KEY', new Map(), {
  serializer: mapSerializer,
  deserializer: mapDeserializer
}

Note for SSR (server-side rendering)

If you are using Gatsby or other SSR frameworks, such as Next.js, refer to this workaround by @hencatsmith.

You need to make sure that window is available.

const useSsrLocalStorage = (
  key: string,
  initial: string
): [string, React.Dispatch<string>] => {
  return typeof window === 'undefined'
    ? [initial, (value: string) => undefined]
    : useLocalStorage(key, initial);
};

Demo

demo

Keywords

FAQs

Package last updated on 31 Jan 2022

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