recoil-persistent
v0.0.10
Published
A very simple library for persisting recoil state.
Downloads
11
Maintainers
Readme
recoil-persistent
A very simple library for persisting recoil state.
Installation
npm install recoil-persistent
Usage
Pass recoilPersistent()
to the Recoil's effects
param. That's it!
import { atom, useRecoilState, useResetRecoilState } from 'recoil';
import recoilPersistent from 'recoil-persistent';
type CounterAtom = number;
const counterAtom = atom<CounterAtom>({
key: 'counterAtom',
default: 0,
effects: [recoilPersistent()], // 👈 All you need to do is just add this line.
});
export default function App() {
const [count, setCount] = useRecoilState(counterAtom);
const resetCount = useResetRecoilState(counterAtom);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount((prev) => prev + 1)}> +1 </button>
<button onClick={() => setCount((prev) => prev - 1)}> -1 </button>
<button onClick={() => resetCount()}>Reset</button>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
);
}
Example
Option
By default, recoil-persistent use window.sessionStorage
where to store persistent data.
If you want to use window.localStorage
, pass it to argument.
const counterAtom = atom<CounterAtom>({
key: 'counterAtom',
default: 0,
effects: [recoilPersistent(window.localStorage)],
});