React hook for saving & hydrating state from local storage, session storage, or cookies
Note: This is using the new React Hooks API Proposal which is subject to change until React 16.7 final.
You'll need to install
react
,react-dom
, etc at^16.7.0-alpha.0
yarn add persistence-hooks
Let's say you want a component to read from & store state in local storage:
import { useStateAndLocalStorage } from 'persistence-hooks'
function MyComponent() {
const INITIAL_VALUE = 'hello world'
const STORAGE_KEY = 'myComponentLocalStorageKey'
const [value, setValue] = useStateAndLocalStorage(
INITIAL_VALUE,
STORAGE_KEY,
)
// use value & setValue just as you would if returned from `useState`
// ...
}
useStateAndLocalStorage
useStateAndSessionStorage
useStateAndCookie
All 3 strategies take in the following arguments:
initial
: the default value when no value has been persisted
key
: the entry in the given persisted strategy to set and draw from
In useStateAndCookie
, a 3rd argument can be passed to specify expiration. Here's the same example above, but using a 10-second cookie:
import { useStateAndCookie } from 'persistence-hooks'
function MyComponent() {
const INITIAL_VALUE = 'hello world'
const STORAGE_KEY = 'myComponentLocalStorageKey'
const [value, setValue] = useStateAndCookie(
INITIAL_VALUE,
STORAGE_KEY,
{ days: 1 / 24 / 60 / 60 * 10 },
)
// ...
}
For more examples, check out the source.
Cheers 🍻