[Redux] Ducks Pattern

Dodam·2024년 1월 28일
0

[Redux]

목록 보기
7/11
post-thumbnail

Duck file

  • 액션 타입(Actions), 액션 생성 함수(Action Creators), 리듀서(Reducer), 그리고 Side Effects까지 모아놓은 파일을 의미한다.

  • Duck file들로 리덕스에 필요한 요소들을 관리하는 것을 덕스(Ducks) 패턴이라고 한다.

Actions :
action의 type을 나타내는 이름

Reducer :
각각의 Action을 처리하는 역할을 하는 함수

Action Creators :
Action 객체를 생성하는 함수

Side effects :
Reducer가 아닌 외부와 연관된 동작들을 의미

Ducks Pattern

액션 타입, 액션 생성 함수, 리듀서를 하나의 모듈처럼 한 파일 안에 작성하고 관리하는 패턴

Ducks 파일의 규칙

  1. 리듀서 함수를 default export 해야 한다.
  2. 액션 생성 함수를 export 해야 한다.
  3. 접두사를 붙인 형태로 액션 타입을 정의해야 한다.
    • 모듈 또는 애플리케이션 이름, 리듀서 이름, ACTION_TYPE을 슬래시로 구분해서 순서대로 써야 함
// Actions (Action Types)
const SET_COUNT = 'my-app/counter/SET_COUNT';
const INCREASE = 'my-app/counter/INCREASE';
const DECREASE = 'my-app/counter/DECREASE';
  1. 액션 타입은 영어 대문자만을 사용하여 SNAKE_CASE 형태로 이름 짓고,
    외부에서 액션 타입을 필요로 할 경우에는 export할 수 있다.

Duck file 예시

// 액션 타입
const SET_COUNT = 'my-app/counter/SET_COUNT';
const INCREASE = 'my-app/counter/INCREASE';
const DECREASES = 'my-app/counter/DECREASE';
// 덕스 패턴에서는 액션 타입을 정의할 때, 다른 모듈과 이름이 중복되지 않도록 접두사를 붙인다.


// 리듀서
export default function reducer(state = 0, action ={}) {
	switch (action.type) {
		case SET_COUNT:
			return action.count;
		case INCREASE:
			return state + 1;
		case DECREASE:
			return state - 1;
	}
}


// 액션 생성 함수
export function setCount(count) {
	return { type: SET_COUNT, count: count };
}
// export const setCount = count => ({ type: SET_COUNT, count });

export function increase() {
	return { type: INCREASE };
}
// export const increase = () => ({ type: INCREASE });

export function decrease() {
	return { type: DECREASE };
}
// export const decrease = () => ({ type: DECREASE });


// 필요한 경우 Side Effects 작성
export function getCount() {
	return dispatch => get('/count').then(count => dispatch(setCount(count)));
}
profile
Good things take time

0개의 댓글