Created
March 3, 2019 22:39
-
-
Save artisonian/9c364c50aa7d267ae1b44c942fb43d8e to your computer and use it in GitHub Desktop.
Bringing back the central dispatcher from Flux, but this time with hooks
This file contains 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
import { useEffect, useReducer } from "react"; | |
const dispatchers = new Map(); | |
function centralDispatch(type, payload) { | |
for (const dispatch of dispatchers.keys()) { | |
dispatch({ type, payload }); | |
} | |
} | |
export function useFlux(reducer, initialState, initializer) { | |
const [state, localDispatch] = useReducer(reducer, initialState, initializer); | |
useEffect(() => { | |
dispatchers.set(localDispatch, true); | |
return () => dispatchers.delete(localDispatch); | |
}, [localDispatch]); | |
return state; | |
} | |
export function useDispatch() { | |
return centralDispatch; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment