useLocalStorage
A hook to manage data in localStorage.
The useLocalStorage hook allows you to persist state in the browser's localStorage. It works similarly to useState but synchronizes the data with local storage so that it persists across page reloads.
It also listens for changes to the local storage key from other tabs/windows and updates the state accordingly.
Demo
Stored Value (in localStorage):
default value
Type something above. If you reload the page, the value will persist.
Source Code
Copy this code into src/hooks/useLocalStorage.ts:
import { useState, useEffect } from 'react';
export const useLocalStorage = <T,>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error('Error reading localStorage key:', key, error);
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error('Error setting localStorage key:', key, error);
}
}, [key, storedValue]);
useEffect(() => {
const handleStorageChange = (event: StorageEvent) => {
if (event.key === key && event.newValue) {
setStoredValue(JSON.parse(event.newValue));
}
};
window.addEventListener('storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [key]);
return [storedValue, setStoredValue] as const;
};Usage
import { useLocalStorage } from '@/hooks/useLocalStorage';
const ThemeToggle = () => {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current Theme: {theme}
</button>
);
};API Reference
Parameters
| Name | Type | Description |
|---|---|---|
key | string | The key used to store the value in localStorage. |
initialValue | T | The initial value if the key does not exist. |
Return Value
| Type | Description |
|---|---|
[T, React.Dispatch<React.SetStateAction<T>>] | Returns a stateful value and a function to update it. |