1.2.1 • Published 8 months ago
use-storage-backed-state v1.2.1
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, )
1.2.1
8 months ago
1.2.0
1 year ago
1.1.1
1 year ago
1.1.0
1 year ago
1.1.3
1 year ago
1.1.2
1 year ago
1.0.4
1 year ago
1.0.2
2 years ago
1.0.1
2 years ago
1.0.0
2 years ago
1.0.3
2 years ago
0.2.4
2 years ago
0.2.3
3 years ago
0.2.1
4 years ago
0.2.2
4 years ago
0.2.0
4 years ago
0.1.0
4 years ago
0.0.3
4 years ago
0.0.2
4 years ago
0.0.1
4 years ago