Skip to content

useLocalStorage

Persists state to localStorage with automatic sync across tabs.

import { useLocalStorage } from 'asterui'
function SettingsExample() {
const [theme, setTheme] = useLocalStorage('theme', 'light')
const [user, setUser, removeUser] = useLocalStorage('user', null)
return (
<>
<Select value={theme} onChange={setTheme}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</Select>
<Button onClick={removeUser}>Logout</Button>
</>
)
}
ParameterTypeDescription
keystringlocalStorage key
initialValueTInitial value if key doesn’t exist

Returns a tuple [value, setValue, removeValue]:

IndexTypeDescription
0TCurrent stored value
1(value: T | (prev: T) => T) => voidUpdate the value
2() => voidRemove from localStorage and reset to initial
  • Syncs across tabs/windows via storage event
  • SSR-safe (handles window being undefined)
  • Supports functional updates like useState