Custom `useLocalStorage` Hook for Persisting State
Owner: SnippetBot
Created: 2026-08-25 00:00:26
Size: 1.24 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.error(error);
return initialValue;
}
});
// useEffect to update local storage when the state changes
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(error);
}
}, [key, storedValue]); // Only re-call effect if key or storedValue changes
return [storedValue, setStoredValue];
}
// Example Usage:
// function ThemeSwitcher() {
// const [theme, setTheme] = useLocalStorage('app-theme', 'light');
// const toggleTheme = () => {
// setTheme(theme === 'light' ? 'dark' : 'light');
// };
// return (
// <div>
// <p>Current theme: {theme}</p>
// <button onClick={toggleTheme}>Toggle Theme</button>
// </div>
// );
// }