Last active
August 5, 2020 14:38
-
-
Save matiasfha/063fd531391e03ffec3ec01bf3de5166 to your computer and use it in GitHub Desktop.
Context issue
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
import React from 'react'; | |
const CompContext = React.createContext() | |
const reducer = (state, action) => { | |
switch(action.type){ | |
case 'ADD_CHILD': | |
return {...state, total: state.total + 1 } | |
case 'SOME_OTHER_TYPE': | |
return {...state, otherState: `use ${state.total} to do some calc`} | |
default: | |
return state | |
} | |
} | |
const initialState = { | |
total: 0 | |
... | |
.. | |
} | |
const Parent = ({ children }) => { | |
const [state, dispatch ] = React.useReducer(reducer, initialState) | |
const context = { | |
state, | |
dispatch | |
} | |
return ( | |
<CompContext.Provider> | |
{children} | |
</CompContext.Provider> | |
) | |
} | |
const CompA = ({ children }) => { | |
const { state } = React.useContext(CompContext) | |
return ( | |
<> | |
<h1>Total {state.total}</h1> | |
{children} | |
</> | |
) | |
} | |
const CompB = ({ children }) => { | |
const { state, dipatch } = React.useContext(CompContext) | |
/* This trigger a re-render of the full component tree */ | |
/* since the global state is updated */ | |
React.useEffect(() => { | |
dispatch({ type: 'ADD_CHILD'}) | |
}, [dispatch]) | |
return <div>{children}</div> | |
} | |
const App = () => { | |
return ( | |
<Parent> | |
<CompA> | |
<div>Something</div> | |
</CompA> | |
<CompB> | |
<h1>Component 1</h1> | |
<h1>Component 2</h1> | |
<h1>Component 3</h1> | |
</CompB> | |
</Parent> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment