/
index.ts
38 lines (32 loc) · 977 Bytes
/
index.ts
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 { Dispatch, useCallback, useEffect, useState } from 'react';
export default function useLocalStorage(
key: string,
initialValue: string = ''
): [string, Dispatch<string>] {
const [value, setValue] = useState(
() => window.localStorage.getItem(key) || initialValue
);
const setItem = (newValue: string) => {
setValue(newValue);
window.localStorage.setItem(key, newValue);
};
useEffect(() => {
const newValue = window.localStorage.getItem(key);
if (value !== newValue) {
setValue(newValue || initialValue);
}
});
const handleStorage = useCallback(
(event: StorageEvent) => {
if (event.key === key && event.newValue !== value) {
setValue(event.newValue || initialValue);
}
},
[value]
);
useEffect(() => {
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, [handleStorage]);
return [value, setItem];
}