useLocalStorage
Manage local storage with ease in React applications.
useLocalStorage provides a straightforward API to read and update values stored in localStorage, automatically handling JSON serialization and deserialization.
Loading...
Install
npx shadcn@latest add https://unlogg.com/r/use-local-storage.jsonpnpm dlx shadcn@latest add https://unlogg.com/r/use-local-storage.jsonbunx shadcn@latest add https://unlogg.com/r/use-local-storage.jsonNotes
- Automatically initializes
localStoragewith a default value if the key does not exist. - Handles JSON serialization and deserialization for complex data types.
- Provides a simple API for reading and updating values.
- Includes error handling for environments where
localStorageis unavailable (e.g., server-side rendering).
Examples
Todo List with Persistence
Loading...
Use Cases
- Theme Preferences: Store user's preferred color scheme, theme settings, or UI preferences
- Form Data: Persist form inputs to prevent data loss during accidental page refreshes
- Shopping Cart: Save cart items locally before user authentication
- User Settings: Store user-specific configuration options and preferences
- Todo Lists: Maintain task lists that persist across browser sessions
- Recently Viewed: Track recently accessed items or pages
- Feature Flags: Store client-side feature toggle states
Server-Side Rendering
This hook checks if localStorage is available before accessing it. If used in a non-browser environment (e.g., during server-side rendering), it will return the defaultValue without attempting to access localStorage.
API Reference
Parameters
| Prop | Type | Default |
|---|---|---|
defaultValue? | T | - |
key? | string | - |
Returns
| Prop | Type | Default |
|---|---|---|
setValue? | (value: T) => void | - |
value? | T | - |