-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseLocalState.js
32 lines (27 loc) · 901 Bytes
/
useLocalState.js
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
import { useState, useEffect } from "react";
export const useLocalState = (key, defaultValue) => {
const [value, setValue] = useState(() => {
const storedValue = localStorage.getItem(key);
return storedValue === null ? defaultValue : JSON.parse(storedValue);
});
useEffect(() => {
const listener = e => {
if (e.storageArea === localStorage && e.key === key) {
setValue(JSON.parse(e.newValue));
}
};
window.addEventListener("storage", listener);
return () => {
window.removeEventListener("storage", listener);
};
}, [key]);
const setValueInLocalStorage = newValue => {
setValue(currentValue => {
const result =
typeof newValue === "function" ? newValue(currentValue) : newValue;
localStorage.setItem(key, JSON.stringify(result));
return result;
});
};
return [value, setValueInLocalStorage];
};