Hooks
No hooks found in any category.
useLocalStorage
stateInstallation
npx usehooks-cli@latest add use-local-storage
Description
A React hook for managing localStorage with automatic JSON serialization/deserialization and React state synchronization.
Parameters
Name | Type | Default | Description |
---|---|---|---|
key | string | - | The localStorage key to use for storing the value |
initialValue | T | - | The initial value to use if no value exists in localStorage |
Return Type
[T, (value: SetValue<T>) => void]
Property | Type | Description |
---|---|---|
storedValue | T | The current value from localStorage or initial value |
setValue | (value: SetValue<T>) => void | Function to update the value in both state and localStorage |
Examples
Basic Usage
Storing and retrieving a simple value
1const [name, setName] = useLocalStorage('user-name', 'Anonymous');
2
3return (
4 <div>
5 <p>Hello, {name}!</p>
6 <input
7 value={name}
8 onChange={(e) => setName(e.target.value)}
9 placeholder="Enter your name"
10 />
11 </div>
12);
Complex Object Storage
Storing and updating complex objects
1interface UserSettings {
2 theme: 'light' | 'dark';
3 notifications: boolean;
4}
5
6const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {
7 theme: 'light',
8 notifications: true
9});
10
11// Update using function
12const toggleTheme = () => {
13 setSettings(prev => ({
14 ...prev,
15 theme: prev.theme === 'light' ? 'dark' : 'light'
16 }));
17};
Dependencies
react
Notes
- •Automatically handles JSON serialization and deserialization
- •Gracefully handles localStorage errors (e.g., in private browsing mode)
- •Supports functional updates like useState
- •Initial value is used as fallback when localStorage is unavailable or parsing fails
- •Works with any JSON-serializable data type
Implementation
1'use client';
2
3import { useState } from "react";
4
5type SetValue<T> = T | ((val: T) => T);
6
7export function useLocalStorage<T>(
8 key: string,
9 initialValue: T
10): [T, (value: SetValue<T>) => void] {
11 const [storedValue, setStoredValue] = useState<T>(() => {
12 try {
13 const item = window.localStorage.getItem(key);
14 return item ? JSON.parse(item) : initialValue;
15 } catch (error) {
16 console.log(error);
17 return initialValue;
18 }
19 });
20
21 const setValue = (value: SetValue<T>) => {
22 try {
23 const valueToStore =
24 value instanceof Function ? value(storedValue) : value;
25 setStoredValue(valueToStore);
26 window.localStorage.setItem(key, JSON.stringify(valueToStore));
27 } catch (error) {
28 console.log(error);
29 }
30 };
31
32 return [storedValue, setValue];
33}
34