Skip to content

Instantly share code, notes, and snippets.

@dominictobias
Last active January 29, 2020 14:51
Show Gist options
  • Save dominictobias/b9d96705b35ac296a561efaac29935f2 to your computer and use it in GitHub Desktop.
Save dominictobias/b9d96705b35ac296a561efaac29935f2 to your computer and use it in GitHub Desktop.
useGlobalState
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];
}
@dominictobias
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment