Skip to content

Instantly share code, notes, and snippets.

@michalvichy
Created October 5, 2019 21:57
Show Gist options
  • Save michalvichy/84af5c7ea7443a8b9f6fb6a7af56e1df to your computer and use it in GitHub Desktop.
Save michalvichy/84af5c7ea7443a8b9f6fb6a7af56e1df to your computer and use it in GitHub Desktop.
Multiple contexts with useReducer() and useMemo()
const ContextA = createContext(null);
const ContextB = createContext(null);
const ContextC = createContext(null);
const App = () => {
const [stateA, dispatchA] = useReducer(reducerA, initialStateA);
const [stateB, dispatchB] = useReducer(reducerB, initialStateB);
const [stateC, dispatchC] = useReducer(reducerC, initialStateC);
const valueA = useMemo(() => [stateA, dispatchA], [stateA]);
const valueB = useMemo(() => [stateB, dispatchB], [stateB]);
const valueC = useMemo(() => [stateC, dispatchC], [stateC]);
return (
<ContextA.Provider value={valueA}>
<ContextB.Provider value={valueB}>
<ContextC.Provider value={valueC}>
...
</ContextC.Provider>
</ContextB.Provider>
</ContextA.Provider>
);
};
const Component1 = () => {
const [stateA, dispatchA] = useContext(ContextA);
return (
...
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment