persistence-hooks
v1.1.0
Published
React hooks that blur the line between state and persistent data
Downloads
10
Readme
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'
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`
// ...
}
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'
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 🍻