목차
1. useReducer 훅이란?
2. useReducer 구성요소
2-1) useReducer 함수
2-2) dispatch 함수
2-3) 3. reducer 함수
1. useReducer 훅이란?
useRedcuer Hook은 react가 상태관리를 위한 reducer function에 접근할 수 있게 해준다.
useState Hook과 매우 비슷한데, 차이점이라면 useReducer는 좀 더 복잡한 로직과 상태관리에서 사용되는 경우가 많다.
2. useReducer 구성요소
1. useReducer 함수
import React, { useReducer } from "react";
const [state, dispatch] = useReducer(reducer, initialState, init);
1. state
- 컴포넌트에서 사용할 상태
2. dispatch 함수
- 첫번째 인자인 reducer 함수를 실행시킨다.
- 컴포넌트 내에서 state의 업데이트를 일으키키 위해 사용하는 함수
3. reducer 함수
- 컴포넌트 외부에서 state를 업데이트 하는 함수
- 현재state, action 객체를 인자로 받아, 기존의 state를 대체하여 새로운 state를 반환하는 함수
4. initialState
- 초기 state
5. init
- 초기 함수 (초기 state를 조금 지연해서 생성하기 위해 사용)
2. dispatch 함수
- reducer 함수를 실행 시킨다.
- action 객체를 인자로 받으며 action 객체는 어떤 행동인지를 나타내는 type 속성과 해당 행동과 관련된 데이터(payload)를 담고 있다.
- action을 이용하여 컴포넌트 내에서 state의 업데이트를 일으킨다.
action은 다음의 예시와 같이 사용 한다.
ex1) action type만 정의하여 사용
<button onClick={() => dispatch({ type: "INCREMENT" })}>증가</button>
ex2) action type과, 데이터를 정의하여 사용
<button onClick={() => dispatch({ type: "INCREMENT", payload: 1 })}>증가</button>
3. reducer 함수
- 상기 dispatch 함수에 의해 실행되며, 컴포넌트 외부에서 state를 업데이트 하는 로직을 담당한다.
- 함수의 인자로는 state와 action을 받게 된다.
- state와 action을 활용하여 새로운 state를 반환 한다.
ex1) action type만 정의하여 사용
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
throw new Error("unsupported action type: ", action.type);
}
}
ex2) action type과, 데이터를 정의하여 사용
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + action.payload };
case "DECREMENT":
return { count: state.count - action.payload };
default:
throw new Error("unsupported action type: ", action.type);
}
}
deposit, withdraw 예제
import React, { useState, useReducer } from 'react';
const ACTION_TYPES = {
deposit: 'deposit',
withdraw: 'withdraw',
};
const reducer = (state, action) => {
console.log('reducer is working now', state, action);
switch (action.type) {
case ACTION_TYPES.deposit:
return state + action.payload;
case ACTION_TYPES.withdraw:
return state - action.payload;
default:
return state;
}
};
function App() {
const [number, setNumber] = useState(0);
const [money, dispatch] = useReducer(reducer, 0);
return (
<div>
<p>잔고: {money}원</p>
<input
type='number'
value={number}
onChange={(e) => setNumber(parseInt(e.target.value))}
step='1000'
/>
<button
onClick={() => {
dispatch({type: ACTION_TYPES.deposit, payload: number})
}}>예금</button>
<button
onClick={() => {
dispatch({type: ACTION_TYPES.withdraw, payload: number})
}}
>출금</button>
</div>
);
}
export default App;
'Client > React.js' 카테고리의 다른 글
[React] Axios 인터셉터 사용법 (0) | 2023.08.30 |
---|---|
[React] Redux 이해하기 (0) | 2023.08.28 |
[React] useCallback (0) | 2023.08.25 |
[React] useMemo (0) | 2023.08.18 |
[React] useEffect (컴포넌트의 Lifecycle, clean up function) (0) | 2022.08.17 |