Skip to content

Instantly share code, notes, and snippets.

@artisonian
Created March 3, 2019 22:39
Show Gist options
  • Save artisonian/9c364c50aa7d267ae1b44c942fb43d8e to your computer and use it in GitHub Desktop.
Save artisonian/9c364c50aa7d267ae1b44c942fb43d8e to your computer and use it in GitHub Desktop.
Bringing back the central dispatcher from Flux, but this time with hooks
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