Redux로 상태관리하기 - Redux Basic 2

lbr·2022년 8월 16일
0

createStore

createStore 함수는 redux에서 가져와서 사용합니다.

const store = createStore(리듀서);

스토어를 만들게 되면,
스토어 안에 있는 상태와 상태를 변경하는 액션을 보내서 각종 state 관리를 할 수 있게 됩니다.

createStore<S>(
  reducer: Reducer<S>,
  preloadedState: S,
  enhancer?: StoreEnhancer<S>
): Store<S>;

createStore는 인자로 3개가 사용됩니다.
첫번째 인자 : reducer 함수
두번째 인자 : preloadedState (여기에 initialstate를 넣을 수 있습니다. 넣지 않으면 각각의 리듀서에서 최초값으로 undefined가 들어오기 때문에 그쪽에서 initialstate를 설정해 줄 수도 있습니다.)
세번째 인자 : enhancer (지금은 배우지 않습니다.)

store 만들어보기

import { createStore } from "redux";
import { todoApp } from "./reducers";

// 1. createStore를 실행하고 이 안에 reducer를 넣겠습니다.
// 2. 다른 js파일에 만들어 둔 reducer를 export하여 이 파일로 import합니다.
const store = createStore(todoApp);

export default store;

이 store를 한번 index.js에 포함시켜서 console.log로 store 객체를 확인해보겠습니다.

아래는 console.log로 확인한 store 객체

dispatch, getState, replaceReducer, subscribe 이 4개의 함수를 한 번 확인해보겠습니다.

이 중에서 눈에 띄는 함수는 getState 입니다.
store에 .getState를 하면 현재의 state의 상태가 출력됩니다.

store.getState()

아래는 console.log로 확인한 store.getState()

빈 배열이 나옵니다.
빈 배열이 나오는 이유는 우리가 위에서 createStore를 할 때, 인자로 넣은 reducers가 최초로 실행되고, previousState가 undefined로 지정되었기 때문에 default 값으로 지정한 initialState가 값으로 지정되고 이것이 그대로 return 되었기 때문입니다.

store.dispatch(action)

dispatch 함수는 action을 인자로 가지고 있습니다.
아래처럼 action을 객체를 인자로 넣으면..

store.dispatch({ type: ADD_TODO });

하지만 우리가 직접 리터럴로 작성할 것이 아니라,
이전에 우리는 액션을 생성하는 함수를 사용하기로 했습니다.

export로 액션을 생성하는 함수를 가지고 와서 import해줍니다.

store.dispatch(addTodo("coding"));

위처럼 작성하면 type이 ADD_TODO이고, todo 값으로 'coding'이 들어간 객체를 dispatch 보냅니다.
store에 도착하면 store는 state를 변경할 것입니다.

dispatch를 보내고 나서 console로 store.getState()를 확인해보면 아래처럼 저장된 데이터를 확인할 수 있습니다.

store.subscribe()

알시다시피 subscribe는 구독하다라는 의미입니다.

store.subscribe()는 store에 변경사항이 생기는 것을 구독하는 것입니다.

subscribe의 인자로 함수를 넣습니다.
store의 상태가 변경되면 인자로 넣은 함수가 호출됩니다.

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(addTodo("coding"));

코드 윗줄에서 구독설정을 하고 아랫줄에서 store를 변경하면 subscribe에 인자로 주었던 함수가 실행됩니다.

이번에는 아래처럼 작성해보겠습니다.

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(addTodo("coding"));
store.dispatch(addTodo("read book"));
store.dispatch(addTodo("eat"));

아래는 출력결과

이처럼 구독해 놓으면 state 변경이 일어날 때마다 콜백함수가 실행됩니다.

store.subscribe()의 리턴은 함수입니다.
리턴된 함수를 실행하면 구독을 취소합니다.

const unsubscribe = store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(addTodo("coding"));
store.dispatch(addTodo("read book"));
store.dispatch(addTodo("eat"));
unsubscribe();
// 이 아래로는 unsubscribe의 콜백함수가 동작하지 않지만
// store에 dispatch는 원래대로 동작합니다.
store.dispatch(addTodo("coding"));
store.dispatch(addTodo("read book"));
store.dispatch(addTodo("eat"));

정리

store.getState();

현재 store의 state를 가져오는 함수.

store.dispatch(액션); store.dispatch(액션생성자());

액션을 인자로 넣어서 store의 상태를 변경시키는 함수.

store.subscribe(() => {});

store에 변경이 생겼을 때, 콜백함수를 실행.

const unsubscribe = store.subscribe(() => {});

리턴된 unsubscribe를 실행하면 등록한 구독 함수를 제거.

store.replaceReducer(다른리듀서);

원래 가지고 있던 reducer를 다른 reducer로 바꾸는 기능이 있습니다.

다음에는 store가 커질 때, 즉 store 안에 있는 state가 복잡해 질 때 어떻게 처리하는 지에 대해서 배우겠습니다.

0개의 댓글