⚛️ React/정리

Redux 정리 (1) : 기본 파일 구조 및 reducers (rootReducer, initialState, switch문, Store)

Zoeeey 2023. 7. 29. 16:42

본격적인 프로젝트를 처음 만들다가 리덕스에 대한 기초가 부족함을 느껴 이곳저곳에서 배운 내용을 총 정리하려 한다.


기본 파일 구조

다양한 구조를 사용하지만 나는 아래 형식으로 파일 구조를 짰다.

| components
|-- Layout.js
|-- Header.js
|-- Footer.js
...
| pages
|-- Auth.js
|-- Home.js
|-- Join.js
...
| Redux // 이부분!
|-- store.js
|-- actions
|-- |-- itemActions.js
|-- |-- userActions.js
...
|-- reducers
|-- |-- rootReducer.js
|-- |-- itemReducer.js
|-- |-- userReducer.js
...

actions와 reducers 폴더로 나누고 기능별로 각각 이름이 같은 리듀서와 액션을 파일로 만들었다. 리듀서 폴더 안에는 rootReducer.js 파일을 만들어 combine해주었다.


reducers

1. itemReducer.js

item자리는 개발자 마음대로 리듀서의 목적에 따라 작명하면 된다.

이 파일은 일반적으로 아래처럼 작성된다.

const initialState = {
  items: [
    {name: '아이템1', category: '카테고리1',}
    {name: '아이템2', category: '카테고리2',}
    ...
  ],
  bestitems: [],
}
const itemReducer = (state = initialState, action) => {
  switch(action.type) {
    case 'ADD_ITEM':
      return state + 1;
    case 'REMOVE_ITEM':
      return state - 1;
    default:
      return state;
  }
}

위 코드에서 itemReducer 함수는 initialState 객체를 초기 상태로 가지며, items와 bestitems라는 상태를 관리한다. 또한 두 가지의 액션 타입을 처리하고 있다. 자세한 설명은 아래와 같다.

1-1. initialState

초기상태를 정의하는 객체다.

1-2. Reducer 함수 파라미터

파라미터 부분의 state는 state, action이 들어간다. state는 reducer파일 내에 initialState가 들어가게 되므로 state = initialState로 많이 쓴다.

1-3. switch문 case

action의 type에 따라 해당 작업을 수행하는 동기문이다.

1-4. switch문 default

useReducer에서는 default가 throw new Error('Unhandled Action')같이 에러를 반환하게 작성하지만, redux에서는 그냥 state만 반환하게 작성한다.


2. rootReducer.js

위처럼 reducer 파일들을 작성한 후, rootReducer.js 파일을 만들어 각 reducer들을 combine해주었다.

import { combineReducers } from 'redux';
import userReducer from './userReducer';
import itemReducer from './itemReducer';

const rootReducer = combineReducers({
  user: userReducer,
  item: itemReducer,
});

export default rootReducer;

이를 통해 여러 개의 리듀서 함수를 하나로 결합해서 단일 리듀서를 생성할 수 있다.


Store.js

이렇게 생성한 rootReducer를 store.js로 연결하여 리덕스 스토어를 생성한다.

import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers/rootReducer';
import logger from 'redux-logger'

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
})


export default store;

(createStore를 사용할 수도 있지만, toolkit으로 configureStore를 사용하면 더욱 더 간편하고 유지보수성이 좋은 store를 생성할 수 있다.)

Redux의 Store는 한 애플리케이션(웹 앱, 모바일 앱 등등)에 대한 상태를 저장하는 '중앙 상태(State) 저장소'다. Store 안에 현재의 앱 상태(State)와 리듀서(Reducer)가 들어있는 것이다.

이렇게 Store를 생성하면 컴포넌트에서 이 Store를 활용하여 상태(State)를 관리하고 업데이트할 수 있다.


연결된 포스트

다음은 Actions.js에 대해 정리한다.

https://sunshineyellow.tistory.com/163

 

Redux 총정리 (2) : actions (액션생성자함수, type, payload)

actions action은 상태(State)에 변화를 발생시키는 객체이다. action 객체는 type 필드를 필수로 가지고 있어야 하며, 그 외의 값은 개발자 맘대로 넣을 수 있다. 참고로 ajax로 json 데이터를 받아올 때는 a

sunshineyellow.tistory.com

그다음 포스팅은 component(컴포넌트)가 상태(state)를 업데이트하는 과정과 dispatch, useSelector를 간단히 정리한다.

https://sunshineyellow.tistory.com/164

 

Redux 총정리 (3) : dispatch, useSelector, 컴포넌트가 상태를 업데이트하는 과정 총정리

dispatch dispatch는 Store의 메서드로, action을 Store에 전달하여 발생시키는 역할을 한다. store.dispatch(action)의 형태로 사용한다. subscribe subscribe는 Store의 메서드로, Store의 state(상태)가 변경될 때마다 특

sunshineyellow.tistory.com


출처 : React document, 벨로퍼트, ZeroCho, chatGPT