useReducer는 리액트의 훅 중 하나로, 상태 관리를 위해 사용됩니다. 이 훅은 복잡한 상태 로직을 다루기 위한 대안으로서, 특히 상태가 여러 부분에 걸쳐 변할 때 또는 다양한 액션에 따라 상태를 업데이트할 때 유용합니다.
간략하게 말하면, useReducer는 컴포넌트의 상태를 관리하는 함수로서, 현재 상태와 액션을 받아서 다음 상태를 반환하는 리듀서 함수와 현재 상태를 나타내는 상태 값, 그리고 액션을 디스패치(dispatch)할 수 있는 함수를 제공합니다.
import { useReducer, useState } from "react";
import countReducer from "../reducer/countReducer";
export default function MyCount() {
const [number, numberDispatch] = useReducer(countReducer, 0);
const [num,setNum] = useState(0);
const handleClick = (event) => {
numberDispatch({ type: event ,number: num})
}
return (
<>
<h1>Count : {number}</h1>
<p>
<button type="button" onClick={()=>handleClick('plus')}>num ++ </button>
<button type="button" onClick={()=>handleClick('minus')}>num -- </button>
<button type="button" onClick={()=>handleClick('reset')}>reset </button><br /><br />
증가치 : <input type="text" value={num} onChange={(e)=>setNum(e.target.value)}/>
</p>
</>
);
}
export default function countReducer(num, action) {
console.log(action);
if (action.type === 'plus') {
return num + parseInt(action.number);
} else if (action.type === 'minus') {
return num - parseInt(action.number);
}
else if (action.type === 'reset') {
return num = 0;
} else {
return
}
}