localStorage
helper
Helper atoms are created using createAtom
. They are similar to the atom
function, except that they add new functionality to the atom using hooks
.
This localStorage
helper can be used to create an atom that will be saved (and fetched if present) to the localStorage
.
Start by creating the atom, providing a key
for the item:
import { localStorageAtom } from 'particule'
export const textAtom = localStorageAtom('mykey')('Hello World')
Use it the same way as you would with an atom:
function App() {
const [value, setValue] = useAtom(textAtom)
return (
<div>
<h1>{value}</h1>
<button onClick={() => setValue('Updated!')}>
Change text
</button>
</div>
)
}
The atom will automatically use the value from localStorage
if it exists, or use the initial value, and will be saved to localStorage
when it changes.