The useReducer is a react hook that controls the state of the component.
This hook is often used to control the input value.
The feature of this hook is that, unlike useSate, it has decided how to update the state before hand.
・src/Example.js
import { useReducer } from "react";
const reducer = (prev, { type, step }) => {
switch (type) {
case "+":
return prev + step;
case "-":
return prev - step;
default:
throw new Error("Invalid action");
}
};
const Example = () => {
const [state, dispatch] = useReducer(reducer, 0);
const countup = () => {
dispatch({ type: "+", step: 2 });
};
const countdown = () => {
dispatch({ type: "-", step: 3 });
};
return (
<>
<h3>{state}</h3>
<button onClick={countup}>+</button>
<button onClick={countdown}>-</button>
</>
);
};
export default Example;
The `reducer' function updates the state, e.g. using the switch function.
We use the `dispatch' function passing an object parameter like type, step and so on.
・An action of countup.
・An action of countdown.