Home  >  Article  >  Web Front-end  >  React Basics~useReducer/ countup

React Basics~useReducer/ countup

Susan Sarandon
Susan SarandonOriginal
2024-10-13 18:22:29920browse
  • 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.

React Basics~useReducer/ countup

・An action of countdown.

React Basics~useReducer/ countup

The above is the detailed content of React Basics~useReducer/ countup. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn