Overview
TheuseLocalStorage hook provides a simple way to persist state in the browser’s localStorage. It automatically syncs state changes to localStorage and retrieves stored values on mount, with built-in error handling for cases where localStorage is unavailable.
Signature
Parameters
The localStorage key to store the value under
The initial value to use if no value exists in localStorage
Return Value
Returns a tuple containing:storedValue(T): The current value stored in localStoragesetStoredValue: A setter function to update the stored value (same signature as React’suseState)
Usage
Basic Example
Storing Complex Objects
Array Storage
Use Cases
- User Preferences: Store theme settings, language preferences, or UI customizations
- Form State: Persist form data to prevent loss on page refresh
- Shopping Carts: Maintain cart state across sessions
- Feature Flags: Store user-specific feature toggles
- Recently Viewed: Track recently accessed items or pages
Implementation Details
- Values are automatically serialized to JSON when stored and deserialized when retrieved
- Changes to the stored value trigger a
useEffectthat updates localStorage - Error handling is built-in with console warnings for localStorage failures
- Uses the
useWindowhook for safe window access - Initial value is only used if no stored value exists or if parsing fails
Error Handling
The hook gracefully handles cases where:- localStorage is unavailable (e.g., in private browsing mode)
- The stored value cannot be parsed as JSON
- Setting localStorage fails due to quota exceeded