forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLocalStorage.js
More file actions
35 lines (31 loc) · 967 Bytes
/
Copy pathuseLocalStorage.js
File metadata and controls
35 lines (31 loc) · 967 Bytes
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
import { useState, useCallback } from 'react';
/**
* useState backed by localStorage with JSON serialization.
*
* @template T
* @param {string} key
* @param {T} initialValue
* @returns {[T, (value: T | ((prev: T) => T)) => void, () => void]}
*/
export function useLocalStorage(key, initialValue) {
const [stored, setStored] = useState(() => {
try {
const item = localStorage.getItem(key);
return item !== null ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = useCallback((value) => {
setStored((prev) => {
const next = typeof value === 'function' ? value(prev) : value;
try { localStorage.setItem(key, JSON.stringify(next)); } catch { /* quota exceeded */ }
return next;
});
}, [key]);
const remove = useCallback(() => {
localStorage.removeItem(key);
setStored(initialValue);
}, [key, initialValue]);
return [stored, setValue, remove];
}