Last active
January 29, 2020 14:51
-
-
Save dominictobias/b9d96705b35ac296a561efaac29935f2 to your computer and use it in GitHub Desktop.
useGlobalState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useGlobalState(globalState, stateGetter) { | |
const [state, setState] = useState(stateGetter(globalState.state)); | |
// We don't want to re-create the listener as we want to unlisten on unmount | |
// of the component which uses this hook, so we "tunnel" the state in. | |
const stateRef = useRef(state); | |
stateRef.current = state; | |
const listener = useRef(nextState => { | |
const stateUpdate = stateGetter(nextState); | |
if (stateRef.current !== stateUpdate) { | |
setState(stateUpdate); | |
} | |
}); | |
useEffect(() => { | |
globalState.listen(listener.current); | |
return () => globalState.unlisten(listener.current); | |
}, [globalState]); | |
return [state, globalState.dispatch]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Part of https://medium.com/@dominictobias/using-react-hooks-for-global-redux-stores-97c092afe210 article