blob: 70a652adbfa406f19ac5f6f776daf60032f93162 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import { useEffect, useState } from 'react';
export const savePersistedState = (key, value) => {
window.localStorage.setItem(key, JSON.stringify(value));
};
export default (key, defaultValue) => {
const [value, setValue] = useState(() => {
const stickyValue = window.localStorage.getItem(key);
return stickyValue ? JSON.parse(stickyValue) : defaultValue;
});
useEffect(() => {
if (value !== defaultValue) {
savePersistedState(key, value);
} else {
window.localStorage.removeItem(key);
}
}, [key, value]);
return [value, setValue];
};
|