useReducer
import React, { useState, useReducer } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case "ADD": {
return { ...state, count: state.count + 1 };
}
case "SUBTRACT": {
return { ...state, count: state.count - 1 };
}
default: {
return state;
}
}
},
{
count: 0,
}
);
let { count } = state;
const add = () => {
dispatch({ type: "ADD" });
};
const subtract = () => {
if (count > 0) {
dispatch({ type: "SUBTRACT" });
}
};
return (
<div>
<button onClick={subtract}>-</button>
<div>{count}</div>
<button onClick={add}>+</button>
</div>
);
};