0
import React, { useReducer } from "react";
const ACTION = {
INCREASE: "increase",
DECREASE: "decrease",
};
function reducer(state, action) {
switch (action.type) {
case ACTION.INCREASE:
return { count: state.count + 1 };
case ACTION.DECREASE:
return { count: state.count - 1 };
default:
return state;
}
}
function ExampleUseReducer() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
function increaseCount() {
dispatch({ type: ACTION.INCREASE });
}
function decreaseCount() {
dispatch({ type: ACTION.DECREASE });
}
return (
<Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}>
<Stack direction={"row"} alignItems={"center"} gap={5}>
<Button variant="contained" onClick={decreaseCount} disabled={state.count <= 0}>
-
</Button>
<Typography>{state.count}</Typography>
<Button variant="contained" onClick={increaseCount}>
+
</Button>
</Stack>
</Stack>
)
}