localStorageAtom

See source code

Creates a new Atom that persists its value to localStorage.

The atom is automatically synced with localStorage - changes to the atom are saved to localStorage, and the initial value is read from localStorage if it exists. Returns both the atom and a cleanup function that should be called to stop syncing when the atom is no longer needed. If you need to delete the atom, you should do it manually after all cleanup functions have been called.

function localStorageAtom<Value, Diff = unknown>(
  name: string,
  initialValue: Value,
  options?: AtomOptions<Value, Diff>
): [Atom<Value, Diff>, () => void]

Example

const [theme, cleanup] = localStorageAtom('theme', 'light')

theme.get() // 'light' or value from localStorage if it exists

theme.set('dark') // updates atom and saves to localStorage

// When done:
cleanup() // stops syncing to localStorage

Parameters

NameDescription

name

string

The localStorage key and atom name. This is used for both localStorage persistence and debugging/profiling purposes.

initialValue

Value

The initial value of the atom, used if no value exists in localStorage.

options

AtomOptions<Value, Diff>

Optional atom configuration. See AtomOptions.

Returns

[Atom<Value, Diff>, () => void]

A tuple containing the atom and a cleanup function to stop localStorage syncing.

Prev
isUninitialized
Next
react