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>
);
};
'프로그래밍 > ReactJS' 카테고리의 다른 글
vite로 react 시작하기 + 폴더구조 (0) | 2024.03.04 |
---|---|
스와이프 리액트에서 반응형 세팅 (0) | 2024.01.09 |
react framer-motion slide구현 (1) | 2023.11.23 |
framer-motion react,typescript 환경 오류 해 (0) | 2023.11.22 |
toggle 버튼 만들기 로직 (1) | 2023.11.18 |