프로그래밍/ReactJS

useReducer 사용하기

타코코딩 2023. 12. 28. 11:50

https://react.dev/reference/react/useReducer

 

useReducer – React

The library for web and native user interfaces

react.dev

//기본구조
const [state, dispatch] = useReducer(reducer, initialArg, init?)
//countReducer
import React from "react";

const countReducer = (count, action) => {
  if (action.type === "plus") {
    return Number(count)+Number(action.number);
  } else if (action.type === "minus") {
    return count-Number(action.number);
  } else if (action.type === "reset") {
    return 0
  }
};

export default countReducer;
import React, { useReducer, useState } from "react";
import countReducer from "../reducer/countReducer";

const MyCount = () => {
  //   const [count, setCount] = useState(0);
  const [count, countDispatch] = useReducer(countReducer, 0);
  const [number, setNumber] = useState(0);
  const handleplus = () => {
    countDispatch({ type: "plus",number});
  };
  const handleMinus = () => {
    countDispatch({ type: "minus",number });
  };
  const handleReset = () => {
    countDispatch({ type: "reset" });
  };

  function handleChange(e) {
    console.log(e.currentTarget.value);
    setNumber(e.currentTarget.value);
  }
  return (
    <div>
      <h1>Count : {count}</h1>
      <button type="button" onClick={() => countDispatch({ type: "plus",number})}>
        +
      </button>
      <button type="button" onClick={() => countDispatch({ type: "reset" })}>
        reset
      </button>
      <button type="button" onClick={() => countDispatch({ type: "minus",number})}>
        -
      </button>
      <input type="number" value={number} onChange={(e) => handleChange(e)} />
    </div>
  );
};