DEV Community

Cover image for React Basics~useReducer/ countup
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~useReducer/ countup

  • 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;

Enter fullscreen mode Exit fullscreen mode
  • 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.

Image description

・An action of countdown.

Image description

Top comments (0)