Repository navigation
Expand file tree
/
Copy pathuseLocalStorage.ts
More file actions
59 lines (49 loc) · 1.62 KB
/
Copy pathuseLocalStorage.ts
File metadata and controls
59 lines (49 loc) · 1.62 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { useSyncExternalStore, useCallback, useEffect, useRef } from "react";
const useLocalStorage = <T>(
key: string,
initialValue: T,
// eslint-disable-next-line no-unused-vars
): [T, (value: T) => void] => {
// Use ref to track the key for the subscribe function
const keyRef = useRef(key);
// Update the ref in an effect instead of during render
useEffect(() => {
keyRef.current = key;
}, [key]);
// Subscribe to storage events
const subscribe = useCallback((callback: () => void) => {
const handleStorage = (e: StorageEvent) => {
if (e.key === keyRef.current) {
callback();
}
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
// Get snapshot from localStorage
const getSnapshot = useCallback(() => {
const item = window.localStorage.getItem(key);
return item;
}, [key]);
// Server snapshot always returns null
const getServerSnapshot = useCallback(() => null, []);
const storedItem = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
// Parse the stored value, falling back to initial value
const storedValue: T = storedItem ? JSON.parse(storedItem) : initialValue;
const setValue = useCallback(
(value: T) => {
window.localStorage.setItem(key, JSON.stringify(value));
// Dispatch a storage event to trigger re-render
window.dispatchEvent(
new StorageEvent("storage", { key, newValue: JSON.stringify(value) }),
);
},
[key],
);
return [storedValue, setValue];
};
export default useLocalStorage;