Local Storage Utilities
A simple set of utilities to interact safely and conveniently with the browser's Local Storage API. Handles storing, retrieving, and removing typed items with support for custom serialization.
Import
import { getFromLocalStorage, saveToLocalStorage, removeFromLocalStorage } from 'nhb-toolbox';
getFromLocalStorage
Type-safe getter for items stored in local storage with custom deserialization support.
function getFromLocalStorage<T>(key: string, deserialize?: Deserializer<T>): T | null
Usage Examples
- String Value
- Object Value
- Custom Deserialization
- Nonexistent Key
// Given: localStorage.setItem('theme', JSON.stringify('dark'))
const theme = getFromLocalStorage<string>('theme');
// Returns: 'dark'
// Given: localStorage.setItem('user', JSON.stringify({ id: 1, name: 'Jane'}))
const user = getFromLocalStorage<{ id: number; name: string }>('user');
// Returns: { id: 1, name: 'Jane' }
// Handle Date objects properly
const user = getFromLocalStorage<{ name: string; createdAt: Date }>(
'user',
(value: string) => {
const parsed = JSON.parse(value);
return {
...parsed,
createdAt: new Date(parsed.createdAt)
};
}
);
const value = getFromLocalStorage<string>('nonexistent');
// Returns: null
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The key for the local storage item. |
| deserialize | Deserializer<T> | Optional function to convert stored string back to type T. Defaults to JSON.parse. |
Returns
- The parsed value if it exists and can be parsed.
nullif the key does not exist or parsing fails.
saveToLocalStorage
Stores values in local storage with custom serialization support.
function saveToLocalStorage<T>(key: string, value: T, serialize?: Serializer<T>): void
Usage Examples
- Store Primitive
- Store Object
- Custom Serialization
saveToLocalStorage('count', 5);
// localStorage entry: { count: "5" }
saveToLocalStorage('session', { token: 'abc', expires: 123456 });
// localStorage entry: { session: '{"token":"abc","expires":123456}' }
// Handle Date objects and custom formatting
saveToLocalStorage(
'user',
{ name: 'John', createdAt: new Date('2023-01-01') },
(value) => JSON.stringify({
...value,
createdAt: value.createdAt.toISOString() // Convert Date to ISO string
})
);
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The key under which to store the value. |
| value | T | The value to store. |
| serialize | Serializer<T> | Optional function to convert value to string. Defaults to JSON.stringify. |
removeFromLocalStorage
Removes an item from local storage.
function removeFromLocalStorage(key: string): void
Usage Examples
removeFromLocalStorage('theme');
// Removes 'theme' from local storage. No effect if not existing.
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The key to remove from local storage. |
Advanced Serialization Examples
Complex Object with Dates
interface User {
id: number;
name: string;
createdAt: Date;
preferences: Map<string, boolean>;
}
// Save with custom serialization
saveToLocalStorage<User>(
'current-user',
user,
(value) => JSON.stringify({
...value,
createdAt: value.createdAt.toISOString(),
preferences: Array.from(value.preferences.entries())
})
);
// Retrieve with custom deserialization
const savedUser = getFromLocalStorage<User>(
'current-user',
(value) => {
const parsed = JSON.parse(value);
return {
...parsed,
createdAt: new Date(parsed.createdAt),
preferences: new Map(parsed.preferences)
};
}
);
Custom Data Format
// Save as CSV-like format
saveToLocalStorage<number[]>(
'scores',
[95, 87, 92],
(value) => value.join(',')
);
// Parse CSV-like format
const scores = getFromLocalStorage<number[]>(
'scores',
(value) => value.split(',').map(Number)
);
Key Features
- Type Safety: Always get the type you expect by passing a generic.
- Flexible Serialization: Support for custom serialization and deserialization functions.
- Consistent JSON Handling: All data is serialized/deserialized automatically with sensible defaults.
- Error Handling: Gracefully handles common storage errors with console warnings.
- Convenient: One-line store/retrieve/delete for component state, settings, and more.
Limitations
- Browser Environment: Only works in browsers where
localStorageis available. - Storage Limits: Subject to browser storage quotas (typically 5-10MB).
- Synchronous: All operations are synchronous and may block the main thread with large data.
Best Practices
- Use custom serialization for complex objects containing Dates, Maps, Sets, or other non-JSON-native types.
- For large datasets, consider compression or alternative storage solutions.
- Always use the same serialization/deserialization functions for the same data.
Recommended Use Cases
- Persisting user preferences (theme, language, etc.)
- Storing session/user tokens and lightweight user data
- Retaining form state or temporary selections
- Simple caching in single-page applications
- Application settings and configuration
See Also
- Session Storage Utilities for similar functionality scoped to the browser session.
- For React apps, consider using useStorage hook from nhb-hooks package for seamless integration.