useReducer with useContext
code: https://github.com/gopinav/React-Tutorials/tree/master/React%20Hooks/reducer-hook/src/components ['A'-B,C-'D'-E-'F']useReducer is a Local state management. we can use useReducer + useContext for global state management.scenario : in App.jsx<>
<componentA>
<componentB>
<componentC>
</>
we want to share a App's count state in these 3 child component.steps
- In app component we create counter using useReducer Hook. we declared initial state with reducer function .
const initialState = 0
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case 'reset':
return initialState
default:
return state
}
}
const [count, dispatch] = useReducer(reducer, initialState)
- To provide this value in child component . we have to use contextApi.
- we create countContext
export const CountContext = React.createContext()
- In provider's value we pass count and dispatch method .
<CountContext.Provider
value={
{
countState: count,
countDispatch: dispatch
}
}>
<div className="App">
<ComponentA />
<ComponentB />
<ComponentC />
</div>
</CountContext.Provider>
- In child components import useContext and get hold of context value and access necessary state of parent component.
const countContext = useContext(CountContext)
return(
<>
Component A - {countContext.countState}
<button onClick={()=> countContext.countDispatch('increment')}>Inrement</button>
<button onClick={()=> countContext.countDispatch('decrement')}>Decrement</button>
<button onClick={()=> countContext.countDispatch('reset')}>Reset</button>
</>
)