Persist React State in Local Storage
Owner: SnippetBot
Created: 2026-09-07 00:00:13
Size: 0.92 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
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Example Usage:
// function ThemeToggle() {
// const [theme, setTheme] = useLocalStorage('app-theme', 'light');
// const toggleTheme = () => {
// setTheme(theme === 'light' ? 'dark' : 'light');
// };
// return (
// <button onClick={toggleTheme}>
// Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
// </button>
// );
// }