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

@illinois/react-use-local-storage

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@illinois/react-use-local-storage

React hook that persists and syncs state with local storage

  • 1.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

react-use-local-storage

React hook that persists state with the localStorage API. It also automatically syncs state between tabs/windows.

Getting started

npm i @illinois/react-use-local-storage

This hook functions similarly to useState, with the exception of the the caveats listed below. If your state is easily encodable in JSON and you don't use lazy initialization or functional updates, it should be easy to migrate from useState. You'll need to provide a key for getting/setting the item in local storage.

import useLocalStorage from '@illinois/react-use-local-storage'

const MyComponent = () => {
  const [count, setCount] = useLocalStorage('value-key', 0)
  return (
    <>
      <div>Count: {count}</div>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </>
  )
}

Trying it out

git clone https://github.com/illinois/react-use-local-storage.git react-use-local-storage
cd react-use-local-storage
npm install
npm run storybook

This will launch a simple demo with a counter that can be incremented and reset. Try opening the demo in two tabs at once and watch how changes are automatically synced between them!

Caveats/Warnings

  • State is serialized with JSON.stringify and deserialized with JSON.parse. This is done because the localStorage API doesn't support storing anything but strings at present. As such, you should pay special attention to objects that might not handle being round-tripped through JSON, e.g. a Date object.

  • Unlike useState, lazy initialization is not currently supported. A PR adding support would be welcome!

  • Unlike useState, functional updates are not currently supported. A PR adding support would be welcome!

Prior art

Keywords

FAQs

Package last updated on 17 Feb 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