@nicnocquee/use-local-storage-hook
v0.0.5
Published
A custom hook that simplifies storing, retrieving, and clearing any types of data from the local storage including sync with other tabs
Readme
useLocalStorage React Hook
A type-safe, composable React hook for synchronizing state with localStorage, supporting any serializable value, with cross-tab updates and legacy data migration. Powered by superjson for robust serialization.
Features
- Type-safe: Works with any serializable value (string, number, object, array, boolean, Date, null, undefined)
- Cross-tab sync: Updates state across browser tabs/windows
- Legacy migration: Migrates old values to a new, safer format
- Clear API: Get, set, and clear values with a simple tuple
Installation
npm install @nicnocquee/use-local-storage-hook superjsonPeer dependencies:
react>= 18.3.1superjson>= 2.2.2
Usage
import { useLocalStorage } from "@nicnocquee/use-local-storage-hook";
const [value, setValue, clearValue] = useLocalStorage<string>(
"my-key",
"default"
);Example: Storing String
const [name, setName] = useLocalStorage<string>("name", "Alice");Example: Storing Object
const [user, setUser] = useLocalStorage<{ id: number; name: string }>("user", {
id: 1,
name: "Alice"
});Example: Storing Array
const [items, setItems] = useLocalStorage<number[]>("items", [1, 2, 3]);Example: Storing Boolean
const [flag, setFlag] = useLocalStorage<boolean>("flag", false);Example: Clearing a value
const [value, setValue, clearValue] = useLocalStorage("key", "default");
clearValue(); // value becomes undefinedBy default, the value is not actually deleted from localStorage, it just sets it to "cleared" type. In this case, the "data" variable will return undefined.
If you want to actually delete the value from localStorage, you can call the clearValue function with purge set to true.
const [value, setValue, clearValue] = useLocalStorage("key", "default");
clearValue(true); // value becomes "default" because it's the initial valueAPI
const [value, setValue, clearValue] = useLocalStorage<T>(key: string, initialValue?: T);value: The current value from localStorage (orinitialValueif the key is not found in localStorage)setValue(value: T): Sets the value in localStorageclearValue(purge?: boolean): Clears the value. Whenpurgeis true, the value is actually deleted from localStorage and thevaluevariable will return theinitialValueparameter. Otherwise, it just sets it to "cleared" type and thevaluevariable will return undefined.
Testing
This project uses Vitest and @testing-library/react for tests. To run tests:
npm testLicense
MIT
