Skip to content

React에 Redux 써보기 #3

@jjk376

Description

@jjk376

React에 Redux 써보기

1. Redux

Redux란?

  • 예측 가능한 상태(state) 컨테이너
  • 예측 가능한
    • 일관적이다.
    • 환경에 의존 하지 않는다
    • 테스트 하기 쉽다.

Q. 왜 FE 의 상태 관리가 어려울까요?

  1. view 이벤트 -> model 변경 -> (또 다른)model 변경 -> (또 또 다른) model 변경 -> (다른) view 변경 ...
  2. 비동기 동작 (ajax 를 통한 api request..)
    1 + 2 로 인해 어디서? 무엇을? 어떻게? 바꾸는지 예측하기 힘들다.

그래서 redux는 변화가 가능한 시점에 제약(원칙)을 뒀다.

Redux의 원칙

  1. 모든 상태는 하나의 store에서 Tree 구조를 이룬다.
    image
  2. store에 저장된 state값은 읽기 전용이다.
  3. state 변화는 순수 함수를 통해서 동작한다.

Redux의 기본 흐름과 구성.

image

  • store로 부터 state 값을 읽어와서 화면에 노출
  • UI의 이벤트가 발생 하게 되면 action 객체를 store에게 전달
  • store에 전달 되기 전에 reducer 라는 것을 거치면서, 기존state 에서 새로운 state로 변화.

1. Store

  • state 값을 저장
  • action 객체를 받아옴
  • 하나의 Store에 여러 reducer가 결합되어 연결되어 있습니다.
  • state tree의 endpoint는 될 수 있으면 primitive type이 있어야 합니다.

2. Action

  • 객체 입니다.
  • type 이라는 문자열 속성값을 가지고 있습니다.
  • type을 통해서 여러 reducer 중 어떤 reducer에 적용 될지 결정 됩니다.
  • type 이름 규칙은 보통 행동_주체로 정해 진다고 합니다. (이것은 코딩 컨벤션)

3. Reducer

  • action.type에 따라서 기존 state 값에서 새로운 state로 이끌어낼 로직이 있습니다.
  • 반드시 기존 state를 바꿔선 안되며, 새로운 state로 대체(재 할당) 시켜야 합니다. (순수 함수로 작성)
  • reducer를 결합하여 store에 등록 하면 state의 값이 tree 구조로 저장됩니다.

Redux의 기타 궁금한 사항

  • Redux store에 있는 data는 어디에 저장? where-is-redux-store-saved
    : 메모리에 저장된다고 합니다. local storage나 cache, cookie 같은것이 아니라고 하네요.
    그래도 페이지 이동에도 state는 남아 있으니 주의 하면 좋을 것 같아요.
  • Redux의 성능적인 이슈는?
    : Redux에서 말하는 state 변화는, 사실 새로운 state object로 갈아 치우는 것입니다. 따라서 기존 state로 부터 deep copy를 하게 되는데, DeepCopy 하기에 비용이 큰 타입들(Array, Object) 타입을 사용 하게 되면 성능 저하가 있을 것으로 보여요.
  • 브라우저 지원은 어디까지 되는 것인가?
    : does Redux support IE8 es5, 6 shim이 있다면, ie8 까진 지원 된다.
    redux-ie8 과 같은 것도 존재 하지만.. update가 안되고 있어요.

2. React-Redux

React-Redux는 무엇을 하는건가요

  • Redux state값과 React Component의 props 값을 연결해줍니다.
    image

적용 예시

redux

1. action

// unitAction
const CONVERT = "UNIT_CONVERT";

export {CONVERT};
export function convert(unit) {
	return {
		type: CONVERT,
		unit
	};
}

2. reducer

//unitReducer
import {CONVERT} from "unitAction";

// 초기 state 값이 있음에 유의 합시다.
const initialState = {
	unit: "MB"
};

function reducer(state = initialState, {type, unit}) {
	switch (type) {
		case CONVERT: {
			return Object.assign({},
				state, {
					unit
				});
		} // 변화가 있으면 반드시 새로운 상태를 만들어서 return 해줍니다.
		default:
			return state;
	}
}

export default reducer;

3. combineReducers

combineReducers({
	something: someReducer
	unitConvert: unitReducer
})

4. createStore

createStore(rootReducer)

5. Provider

<Provider store={store}>
	<Components />
</Provider>
  • Components는 ReactApp의 최상위 컴포넌트.

6. connect

  • store로 부터 state 값을 읽어오는 컴포넌트
connect(state => ({unit: state.unitConvert.unit}))(SubscribeComponent) 
  • store의 state를 변경하는 컴포넌트
import {convert} from "unitAction";
const dispatchToProps = dispatch => ({
	handleUnit: unit => dispatch(convert(unit))
});
connect(null, dispatchToProps)(PublishComponent)

3. 관련 링크

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions