Local Storage Utilities
Safely and conveniently interact with the browser's Local Storage API, supporting typed items and custom serialization.
Overview
A simple set of utilities to interact with the browser's Local Storage API. Handles storing, retrieving, and removing typed items.
Import
import {
getFromLocalStorage,
saveToLocalStorage,
removeFromLocalStorage
} from 'toolbox-x/dom';getFromLocalStorage
Retrieves and parses an item from local storage, with optional custom deserialization.
Function Signature
function getFromLocalStorage<T>(key: string, deserialize?: Deserializer<T>): T | nullParameters
key(string): The key for the local storage item.deserialize(Deserializer<T>, optional): A function to convert the stored string back to typeT. Defaults toJSON.parse.
Return Value
T | null: The parsed value, ornullif the key does not exist or parsing fails.
Example Usage
import { getFromLocalStorage } from 'toolbox-x/dom';
// Given: localStorage.setItem('theme', JSON.stringify('dark'))
const theme = getFromLocalStorage<string>('theme');
console.log(theme); // Output: 'dark'saveToLocalStorage
Stores a value in local storage, with optional custom serialization.
Function Signature
function saveToLocalStorage<T>(key: string, value: T, serialize?: Serializer<T>): voidParameters
key(string): The key under which to store the value.value(T): The value to store.serialize(Serializer<T>, optional): A function to stringify the value. Defaults toJSON.stringify.
Example Usage
import { saveToLocalStorage } from 'toolbox-x/dom';
saveToLocalStorage('count', 5);removeFromLocalStorage
Removes an item from local storage.
Function Signature
function removeFromLocalStorage(key: string): voidParameters
key(string): The key to remove.
Example Usage
import { removeFromLocalStorage } from 'toolbox-x/dom';
removeFromLocalStorage('theme');Types
type Serializer<T> = (value: T) => string;
type Deserializer<T> = (value: string) => T;See Also
- Session Storage Utilities - For session-scoped browser storage.
Last updated: Mon, Jun 15, 2026 11:04:47AM (UTC)
