useLocalStorage
A hook that persists state in localStorage with the same API as useState.
useLocalStorage
The useLocalStorage
hook provides persistent state storage using the browser’s localStorage API. It works just like React’s useState
hook, but automatically syncs state changes to localStorage, making values persist between page refreshes and browser sessions.
Enter your name above
Refresh the page and your values will persist!
Installation
Install the useLocalStorage hook using:
File Structure
Parameters
Prop | Type | Default |
---|---|---|
key | string | Required |
initialValue | T (generic type) | Required |
Return Value
Prop | Type | Default |
---|---|---|
storedValue | T (generic type) | - |
setValue | (value: T | ((val: T) => T)) => void | - |
Examples
More Examples
Enter your name above
Refresh the page and your values will persist!
Shopping Cart
Persist a shopping cart between sessions:
User Settings
Store user preferences:
Use Cases
- User Preferences: Theme settings, language preferences, UI configurations
- Form State: Save form progress to prevent data loss on refresh
- Authentication: Store authentication tokens (though with caution)
- Shopping Carts: Persist items between sessions
- Application State: Maintain state across page reloads
- Recently Viewed: Track recently viewed items
- Tutorial Progress: Remember completed tutorial steps
- Feature Flags: Store user-specific feature toggles
Synchronization
This hook handles synchronization between:
- Multiple components using the same key - Updates in one component trigger updates in others
- Multiple tabs/windows - Changes in one tab are synchronized to others
This is achieved using:
- Custom events (
local-storage
) for same-window synchronization - Native
storage
events for cross-tab/window synchronization
Security Considerations
When using localStorage, keep these security considerations in mind:
- No Sensitive Data: Never store passwords, authentication tokens (unless required for functionality), or personal information
- XSS Vulnerability: localStorage is accessible to any JavaScript running on your site
- Size Limits: localStorage has a limit of ~5MB per domain
- Client-Side Only: localStorage is unavailable during server-side rendering
Type Safety
The hook is fully typed with TypeScript generics, allowing you to specify the exact type of data you’re storing:
Server-Side Rendering
This hook includes SSR safeguards by checking if window
is defined before accessing browser APIs. During server rendering, it returns the provided initial value.
Best Practices
- Use descriptive, namespaced keys to avoid collisions
- Keep stored values small and serializable
- Provide meaningful initial values
- Implement error handling for parsing issues
- Consider encrypting sensitive data if localStorage must be used
- Clear localStorage when no longer needed
- Use sessionStorage instead if data should not persist between sessions