Ducks 패턴에 의하면 초기값, 액션, 리듀서를 관련 있는 state 별로 modules 폴더에 만들어 관리한다.
const initialState = 0;
const increase = () => ({
type : INCREMENT,
payload : {
incrementValue : 1
}
}); // return이 생략된 형태로 소괄호로 감싸주어야한다.(중괄호만 있을 시 함수로 인식)
const decrease = () => ({
type : DECREMENT,
payload : {
decrementValue : 1
}
});
액션 타입을 상수로 정의한다. 접두사는 다른 모듈과 액션 값이 겹치지 않게하기 위함이다.
const INCREMENT = 'count/INCREMENT';
const DECREMENT = 'count/DECREMENT';
function reducer(state = initialState, action) {
const { payload } = action;
switch(action.type){
case INCREMENT :
return state + payload.incrementValue;
case DECREMENT :
return state - payload.decrementValue;
default :
return state;
}
}
function App() {
const count = useSelector(state => state);
const dispatch = useDispatch();
const increaseCount = () => {
/* 사전에 정의한 액션 함수를 호출*/
dispatch(increase());
}
const decreaseCount = () => {
dispatch(decrease());
}
return (
<>
<h1> Count : { count } </h1>
<button onClick={ increaseCount }>1증가</button>
<button onClick={ decreaseCount }>1감소</button>
</>
);
}
const store = createStore(reducer);
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider store={store}>
<App/>
</Provider>
);