persistence-hooks
React hook for saving & hydrating state from local storage, session storage, or cookies
Install
yarn add persistence-hooks
Usage
Basic Example
Let's say you want a component to read from & store state in local storage:
import useStateAndLocalStorage from 'persistence-hooks' { const INITIAL_VALUE = 'hello world' const STORAGE_KEY = 'myComponentLocalStorageKey' const value setValue = // use value & setValue just as you would if returned from `useState` // ... }
Available Strategies
useStateAndLocalStorage
useStateAndSessionStorage
useStateAndCookie
Arguments
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' { const INITIAL_VALUE = 'hello world' const STORAGE_KEY = 'myComponentLocalStorageKey' const value setValue = // ... }
For more examples, check out the source.
Cheers 🍻