UseState와 비슷하지만 사용하는 방식이 다르다.
아래는 useState를 사용한 예제이다.
const [count, setCount] = useState(0);
return(
<>
<input type="button" value="-" onClick={()=>{setCount(count - 1)}}/>
<input type="button" value={count}/>
<input type="button" value="+" onClick={()=>{setCount(count + 1)}}/>
</>
)
아래는 useReducer를 사용한 예제이다.
function countReducer(oldCount, action) {
if(action === 'UP')
{
return oldCount + 1;
} else if(action === 'DOWN')
{
return oldCount - 1;
} else if(action === 'RESET')
{
return 0;
}
}
function App() {
// useReducer 안에 있는 countReducer는 "함수"를 불러오는 역할이다.
// useReducer 안에 있는 0은 초기값을 의미한다.
const [count, countDispatch] = useReducer(countReducer, 10);
function down() {
//'DOWN'은 action을 의미한다.
countDispatch('DOWN');
}
function reset() {
countDispatch('RESET');
}
function up() {
countDispatch('UP');
}
return(
<>
<input type="button" value="-" onClick={down}/>
<input type="button" value="0" onClick={reset}/>
<input type="button" value="+" onClick={up}/>
<span>{count}</span>
</>
)
}
사용방법에 대해 알아보자
const [count, countDispatch(이부분은 보통 Dispatch라고 적는다고 한다)] = useReducer(countReducer, 0)
useReducer안에 있는 countReducer = 만들어 두었던 함수를 사용할 것이다 선언을 해준것이며 0은 초기값을 의미한다.
countReducer에서 만들어 두었던 action값을 countDispatch를 통해 가져온다.
function down() {
//'DOWN'은 action을 의미한다.
countDispatch('DOWN');
}
function reset() {
countDispatch('RESET');
}
function up() {
countDispatch('UP');
}
Reducer에서는 "주문"을 한다고 생각하자.
useState와 useReducer를 같이 사용
const [number, setNumber] = useState(0);
function countReducer(oldCount, action) {
if(action.type === 'UP')
{
return oldCount + action.number;
}
else if(action.type === 'DOWN')
{
return oldCount - action.number;
}
else if(action.type === 'RESET')
{
return 0;
}
const [count, countDispatch] = useReducer(countReducer, 10);
function down() {
//'DOWN'은 action을 의미한다.
countDispatch({type: 'DOWN', number: number});
}
function reset() {
countDispatch({type: 'RESET', number: number});
}
function up() {
countDispatch({type: 'UP', number: number});
}
function changeNumber(e) {
setNumber(Number(e.target.value));
}
return(
<>
<input type="button" value="-" onClick={down}/>
<input type="button" value="0" onClick={reset}/>
<input type="button" value="+" onClick={up}/>
<input type="text" value={number} onChange={changeNumber}/>
<span>{count}</span>
</>
)
}
지난 예제와 다른점은 if(action.type === 'UP') 부분이다.
지난 예제에서는 countDispatch('DOWN'); 였기 때문에 type을 안붙여도 문제가 없었지만
이번 예제에서는 countDispatch({type: 'DOWN', number: number});로 되어있기 때문에 type을 붙여야된다.
action.number는 countDispatch({type: 'DOWN', number: number});여기서 number값을 주었기 때문에
action.number가 되는것.