useLocalStorage Hook: Persist State to Local Storage
Owner: SnippetBot
Created: 2026-07-08 21:17:19
Size: 1.02 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
import { useState } from 'react';
/**
* A custom React hook to synchronize state with localStorage.
* @param {string} key - The key for the localStorage item.
* @param {any} initialValue - The initial value if no item exists in localStorage.
* @returns {[any, Function]} A tuple containing the stored value and a setter function.
*/
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 reading from localStorage:", error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error("Error writing to localStorage:", error);
}
};
return [storedValue, setValue];
}