Home > Web Front-end > JS Tutorial > body text

React Basics~useReducer/ countup

Susan Sarandon
Release: 2024-10-13 18:22:29
Original
919 people have browsed it
  • 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;

Copy after login
  • 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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!