React Shared Storage is built to be a simple way for storing state in the browsers local storage. It will keep your state synced between different components and different windows and tabs.
Install it with Yarn:
yarn add react-shared-storage
Or NPM:
npm i react-shared-storage
The package exposes the usePersistentState
hook which works similarly to set state. The biggest difference is that you will
also have to provide a key property which is used to identify the property between components and windows.
import { usePersistentState } from 'react-shared-storage'
export function CounterComponent() {
// The `counter` key will be used to identify the value.
const [ counter, setCounter ] = usePersistentState('counter', 0)
return (
<div>
<div>
{ counter }
</div>
<button onClick={ () => setCounter(counter + 1) }>
Increase
</button>
</div>
)
}
export function AnotherComponent() {
// This component will also react to the `counter` value being changed.
const [ counter, setCounter ] = usePersistentState('counter', 0)
return (
<div>
<div>
{ counter }
</div>
<button onClick={ () => setCounter(counter + 1) }>
Increase
</button>
</div>
)
}
If you are want to save the state to local storage, but don't want it to sync between components and windows, you can disable the sync:
usePersistentState('counter', 0, {
shouldSync: false
})
The different options you can pass to the usePersistentState
hook are:
Name | Default Value | Description |
---|---|---|
saveInterval | 200 |
Determines how often the state is saved to local storage. |
shouldSync | true |
Used to enable or disable syncing of state between windows. |
There is a demo app in the demo/
directory that you can use for testing.
Start it with:
yarn demo
There is a linter:
yarn lint
and a test suite:
yarn test
- Fork it (https://github.com/your-github-user/test/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
- Christoffer Artmann - creator and maintainer