Skip to main content
Version: 1.0.0

useLocalStorage

Provides fully typed access to localStorage with automatic JSON serialisation and deserialisation.

Signature​

function useLocalStorage<Type extends Record<string, any>>(): {
getItem: <Key extends keyof Type>(key: Key) => Type[Key] | null;
setItem: (key: keyof Type, value: Type[keyof Type]) => void;
removeItem: (key: keyof Type) => void;
hasItem: (key: keyof Type) => boolean;
clear: () => void;
}

Type parameter​

Pass your storage schema as a generic to get full auto-completion and type safety:

interface MyStorage {
theme: "dark" | "light";
userId: number;
preferences: { lang: string; notifications: boolean };
}

const storage = useLocalStorage<MyStorage>();
storage.setItem("theme", "dark"); // ✅
storage.setItem("theme", "blue"); // ❌ Type error

Return value​

MethodDescription
getItem(key)Returns the typed value, or null if it is not set or is not valid JSON
setItem(key, value)Serialises and stores the value
removeItem(key)Removes the key from storage
hasItem(key)Returns true if the key exists, even if its value is an empty string
clear()Removes all keys from storage
Not reactive

The methods read and write localStorage directly. Calling setItem does not re-render components. Keep the value in state if the UI depends on it.

Error handling​

The hook throws an UnsupportedClient error if window.localStorage is unavailable (e.g., in a server-side rendering context or when storage is blocked by the browser).

Live example​

Loading playground...