1.1.3 • Published 4 months ago
use-storage-backed-state v1.1.3
useStorageBackedState
Custom React hook for storage backed persisted state. Check interactive demo.
Installation
npm install use-storage-backed-state
How to use
import React from 'react'
import { useStorageBackedState } from 'use-storage-backed-state'
export const MyComponent = () => {
// 0: initialState
// 'count': localStorage key
const [count, setCount] = useStorageBackedState(0, 'count')
return (
<section>
<h1>
Value: <output>{count}</output>
</h1>
<button
onClick={() => {
setCount(count + 1)
}}
>
increment
</button>
<button
onClick={() => {
setCount(count - 1)
}}
>
decrement
</button>
</section>
)
}
Notes
Stores data in
localStorage
.Works with
sessionStorage
too.useStorageBackedState(…, …, sessionStorage)
Realtime synchronization between multiple uses with the same
key
. Even across tabs.You can opt out from storage and synchronization by passing
null
as the second argument or by omitting thekey
altogether.useStorageBackedState
will then behave similarly likeuseState
in that case.const [count, setCount] = useStorageBackedState(1)
const [storeState, setStoreState] = useState(false) const [count, setCount] = useStorageBackedState( 1, storeState ? 'count' : null, )