jotai-persistent-atom
v1.0.0
Published
A simple React hook to sync a Jotai atom with localStorage, making it persistent across sessions.
Maintainers
Readme
Jotai Persistent Atom A simple React hook to sync a Jotai atom with localStorage, making your app's state persistent across browser sessions.
The Problem Jotai is fantastic for managing client-side state, but its state is ephemeral. When a user refreshes the page, the state is lost. To persist state for things like user settings or form data, you need to manually write useEffect logic to sync your atoms with localStorage, which can be repetitive and error-prone.
The Solution usePersistentAtom is a drop-in replacement for Jotai's useAtom that handles all the localStorage synchronization for you automatically.
import { atom } from 'jotai'; import { usePersistentAtom } from 'jotai-persistent-atom';
// 1. Define your atom as you normally would. const userSettingsAtom = atom({ theme: 'dark', notifications: true, });
// 2. In your component, use the persistent hook instead of useAtom. function SettingsPanel() { const [settings, setSettings] = usePersistentAtom(userSettingsAtom, 'user-settings-key');
// ... now any changes to settings will be automatically saved!
return ( Theme: <select value={settings.theme} onChange={(e) => setSettings(s => ({ ...s, theme: e.target.value }))} > Dark Light ); }
Installation npm install jotai-persistent-atom
API usePersistentAtom(atom, key) Parameters atom (required): A writable Jotai atom.
key (required): A unique string key to use for storing the value in localStorage.
Returns An array tuple [value, setValue] that is identical to the one returned by Jotai's useAtom.
