Skip to content

Instantly share code, notes, and snippets.

@Vishalll07
Created October 26, 2024 19:11
Show Gist options
  • Save Vishalll07/1f6b46e1ea90d51be7d76368a9cbf958 to your computer and use it in GitHub Desktop.
Save Vishalll07/1f6b46e1ea90d51be7d76368a9cbf958 to your computer and use it in GitHub Desktop.
Advance State Management using useReducer()
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