Created
October 5, 2019 21:57
-
-
Save michalvichy/84af5c7ea7443a8b9f6fb6a7af56e1df to your computer and use it in GitHub Desktop.
Multiple contexts with useReducer() and useMemo()
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
| 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