-
Notifications
You must be signed in to change notification settings - Fork 97
/
usePersistedState.js
43 lines (34 loc) · 1.12 KB
/
usePersistedState.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
33
34
35
36
37
38
39
40
41
42
43
import { useState, useEffect, useRef } from 'react';
import useEventListener from '@use-it/event-listener';
import createGlobalState from './createGlobalState';
const usePersistedState = (initialState, key, { get, set }) => {
const globalState = useRef(null);
const [state, setState] = useState(() => get(key, initialState));
// subscribe to `storage` change events
useEventListener('storage', ({ key: k, newValue }) => {
const newState = JSON.parse(newValue);
if (k === key && state !== newState) {
setState(newState);
}
});
// only called on mount
useEffect(() => {
// register a listener that calls `setState` when another instance emits
globalState.current = createGlobalState(key, setState, initialState);
return () => {
globalState.current.deregister();
};
}, []);
// Only persist to storage if state changes.
useEffect(
() => {
// persist to localStorage
set(key, state);
// inform all of the other instances in this tab
globalState.current.emit(state);
},
[state]
);
return [state, setState];
};
export default usePersistedState;