[리액트] 리덕스(Redux)와 Observer 패턴

Seungho Lee
5 min readMay 13, 2018

여러 디자인 패턴 중 리액트 개발자들은 옵저버패턴(Observer pattern)을 사용합니다. 옵저버패턴은 객체의 변화를 여러 구독자에게 전달하는 것을 말합니다. 이는, 객체들간의 일대 다수(one-to-many)의 연결을 말합니다. 관찰자(subject or observable)는 보통 3개의 메소드를 가집니다(등록, 제거, 알림).

리액트 사용시 데이터 관리를 손쉽게 하기 위해 리덕스(redux)를 사용하며, 이는 옵저버 패턴을 기반으로 제작되었습니다. 리덕스 스토어(store)는 애플리케이션의 상태트리(state tree)를 관리하고 있습니다. 스토어 내부에서 상태값이 변하면 그것에 대한 액션을 보내줘야합니다.

스토어는 간단한 라이브러리이며 몇 가지 메소드를 가지고 있습니다. getState(), dispatch(action), subscribe(listener) 입니다.

function createStore(reducer, initialState) {
let state = initialState;
// Setup listners to keep track of when the state is changed
// to triger rerenders (observer pattern)
const listeners = [];
const subscribe = (listener) => (
listeners.push(listener)
);
const getState = () => (state);const dispatch = (action) => {
state = reducer(state, action);
// call each listener function when the state is changed
// its just a notification that state is changed
listeners.forEach(l => l());
};
return {
subscribe,
getState,
dispatch,
};
}
function reducer(state, action) {
if(action.type === 'ADD_MESSAGE') {
return {
messages: state.messages.concat(action.message),
}
};
if(action.type === 'DELETE_MESSAGE') {
return {
messages: [
...state.messages.slice(0, action.index),
...state.messages.slice(
action.index + 1, state.messages.length
),
],
};
};
return state;
}
// set initial state to pass into to store
const initialState = { messages: [] };
// initialize the store
const store = createStore(reducer, initialState);
class Messages extends React.Component {
componentDidMount() {
store.subscribe(() => this.forceUpdate());
}
render() {
const messages = store.getState().messages;
return (
<div className='ui segment'>
<MessageView messages={messages} />
<MessageInput />
</div>
)
}
}

createStore에서 빈 배열을 생성합니다. 이 곳에 listeners/subscribers를 저장합니다. 다음, subscribe 메소드에서 새로운 subscribers를 등록합니다. 여기에서는 componentDidMount 메소드에서 subscribe를 호출합니다. dispatch는 reducer에 파라미터로 전달되는 액션 타입에 맞는 데이터를 업데이트합니다. 그 이후 등록된 listeners/subscribers에게 변화를 전달합니다. 지금까지 redux 원리와 사용법을 살펴봤습니다.

지금부터는, React-redux를 사용하도록 하겠습니다.

출처

--

--