Created
October 26, 2024 19:11
-
-
Save Vishalll07/1f6b46e1ea90d51be7d76368a9cbf958 to your computer and use it in GitHub Desktop.
Advance State Management using useReducer()
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, { useReducer } from 'react'; | |
const cafeReducer = (state , action) => { | |
switch(action.type) { | |
case 'ADD_ORDER' : | |
return { ...state, orders: state.orders + 1 } ; | |
case 'REMOVE_ORDER' : | |
return { ...state, orders: state.orders - 1 } ; | |
default: | |
return state; | |
} | |
}; | |
const CafeWithReducer = () => { | |
const initialState = {orders: 0 }; // this will be the initialState | |
// use the reducer to manage the cafe's state | |
const [ state, dispatch ] = useReducer(cafeReducer , initialState); | |
return ( | |
<div> | |
<h1>Orders in the Café: {state.orders}</h1> | |
<button onClick={() => dispatch({ type: 'ADD_ORDER' })}>Add Order</button> | |
<button onClick={() => dispatch({ type: 'REMOVE_ORDER' })}>Remove Order</button> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment