잘못 된 내용에 대한 지적은 언제든 환영입니다.
useReducer
useReducer
함수의 구조const [state, dispatch] = useReducer(reducer, initialState);
state
: 현재 상태dispatch
: 액션을 발생시키는 함수이며, reducer
함수의 두 번째 파라미터에 객체를 전달한다. // 보통 type에 상태 업데이트 로직을 구분하는 고유의 문자열을 넣는다.
dispatch({
type: "ON_INCREASE",
number: 1,
});
reducer
: 상태 업데이트 로직을 담은 함수initialState
: 초기 상태reducer
함수의 구조function reducer(state, action) {...}
state
: 현재 상태action
: dispatch
함수를 통해 받은 객체 // 보통 switch-case문을 통해 action.type 값에 따라 수행 할 상태 업데이트 로직을 결정한다.
function reducer(state, action) {
switch (action.type) {
case "ON_INCREASE":
return {
...state,
number: state.number + action.number,
};
default:
return state;
}
}
useReducer
예제 import { useReducer } from "react";
// 상태 업데이트 로직을 담은 reducer 함수
function reducer(state, action) {
switch (action.type) {
case "ON_INCREASE":
return state + action.number;
case "ON_DECREASE":
return state - action.number;
default:
return state;
}
}
function App() {
// useReducer()
const [number, dispatch] = useReducer(reducer, 0);
/* 더하기, 빼기 이벤트 함수에는,
각각 필요한 로직을 사용하기 위해 필요한 값들이 담긴 객체를 dispatch 함수로 넘겨주었다. */
const onIncrease = () => {
dispatch({
type: "ON_INCREASE",
number: 1,
});
};
const onDecrease = () => {
dispatch({
type: "ON_DECREASE",
number: 1,
});
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default App;
References
"20. useReducer 를 사용하여 상태 업데이트 로직 분리하기" .velopert
"React Hooks : useReducer() 함수" .xiubindev