<aside> ✅ 리덕스는 데이터를 어떻게 구조화하느냐에 따라 코드의 방향과 전체적인 구조가 달라진다. 같은 성격의 이벤트끼리 묶어서 그룹화시키는 것이 핵심이다!

</aside>

redux 분리 및 combineReducers 적용

combineReducer로 리듀서 분리

reducer를 별도의 파일로 분리한다. reducer는 분리하기가 쉬운데 그 이유는 순수함수이기 때문이다. (순수함수란 주어진 매개변수와 함수 내부에서 선언한 변수를 제외하고 다른 값을 참조하지 않는 함수이다)

reducers/post.js

const initialState = [];

const postReducer = (prevState = initialState, action) => {
  switch (action.type) {
    case 'ADD_POST':
      return [...prevState, action.data];
    default:
      return prevState;
  }
};

module.exports = postReducer;

reducers/user.js

const initialState = {
  isLoggingIn: false,
  data: null,
};

const userReducer = (prevState = initialState, action) => {
  switch (action.type) {
    case 'LOG_IN':
      return {
        isLoggingIn: !prevState.isLoggingIn,
        data: action.data,
      };
    case 'LOG_OUT':
      return {
        isLoggingIn: !prevState.isLoggingIn,
        user: null,
      };
    default:
      return prevState;
  }
};

module.exports = userReducer;

reducers/index.js

분리한 리듀서를 index.js에서 combineReducers로 merge해준다.

const { combineReducers } = require('redux');
const userReducer = require('./user');
const postReducer = require('./post');

module.exports = combineReducers({
  user: userReducer,
  posts: postReducer,
});

Action 함수 분리

action도 reducers와 비슷하게 actions 폴더로 같은 성격의 데이터로 분리하여 보관한다.

actions/user.js

const logIn = (data) => ({ type: 'LOG_IN', data });
const logOut = () => ({ type: 'LOG_OUT' });

module.exports = { logIn, logOut };

actions/posts.js

const addPost = (data) => ({ type: 'ADD_POST', data });

module.exports = { addPost };

분리한 데이터 호출해오기