개발자를 향해...

[초보자를 위한 리덕스 101] #4.0 Redux Toolkit ~ #4.5 Conclusions 본문

웹 자바스크립트 공부/ReactJS + node.js

[초보자를 위한 리덕스 101] #4.0 Redux Toolkit ~ #4.5 Conclusions

eugeneHwang1124 2021. 3. 10. 22:37
728x90
반응형

본 글은 노마드코더 님의 [초보자를 위한 리덕스 101]을 수강하며 작성하였습니다.

 

#4.0 Redux Toolkit

Redux Toolkit를 사용하면  적은량의 코드로 같은 기능을 구현할 수 있도록한다. 코드가 더 짧아질 수 있다. 

npm install @reduxjs/toolkit

를 실행한다.

 

#4.1 createAction

 action을 사용해보자. store.j로 가서 "ADD", "DELETE" 부분과  addToDO, deleteTodo를 삭제하고 다음 코드를 작성한다.

const addToDo = createAction("ADD");
const deleteToDo = createAction("DELETE");

그리고 import { createAction } from "@reduxjs/toolkit";를 추가한다.

이제 switch부분에서 case도 다음과 같이 수정한다.

switch (action.type) {
    case addToDo.type:
        return [{ text: action.payload, id: Date.now() }, ...state];
    case deleteToDo.type:
        return state.filter(toDo => toDo.id !== action.payload);
    default:
        return state;
    }

console.log(addToDo(), delteToDo());를 실행시키면 두가지의 obejct를 볼 수 있다. type , payload를 볼 수 있다. 

store.js를 보면 action은 text를 가지고 있지 않다. 대신 type를 가지고 있다. 따라서 payload를 주어야한다. 그래서 case에서 리턴 코드를 위와 같이 바꾸었다. 우리가 더이상 action을 정의하지 않아도 된다는 것에 의의가 있다.

 

#4.2 createReducer

createAction보다 좋은 것이있다. createReducer이다.  import한 후에 createReducer를 사용한다.

const reducer = createReducer([],{
    [addToDo]:(state, action)=>{
        state.push({ text: action.payload, id: Date.now() })
    },
    [deleteToDo]: (state, action) =>
        state.filter(toDo => toDo.id !== action.payload)
    
})

여기서는 빈 배열을 넣어주었다. createReducer를 사용하면 더 이상 switch문을 쓰지 않아도 된다는 것에 의의가 있다. 기존에는 새로운 배열을 만들면서 추가가 가능했는데 이제는 굳이 새로운 배열을 만들지 않아도 mutate할 수 있다.

createReducer에는 두가지 옵션이 있다. 새로운 stateㄹㄹ 리턴할 수도 있고 state를 mutate할 수도 있다. 

 

#4.3 configureStore

이제 configureStore 함수를 써보자. default가 추가되어있다. 이를 통해우리의 상태에 어떤 일이 발생했는지 정확하게 알 수 있다.  이전 상태나 현재상태의 state도 볼 수 있다.

Redux Developer Tools를 설치하면 이런 내용들을 쉽게 볼 수 있다. 웹사이트의 상태를 볼 수 있다. 

사용하기 위해서는 store.js에서

const store = createStore(reducer); 대신

const store = configureStore({ reducer });를 사용해야한다. 

 

#4.4 createSlice

createSlice는 우리의 코드를 더 줄여주고 actions도 생성해준다.  store.js에서  import 밑부분을 주석처리해주자.

actions를 생성하기보다는 addToDo를 작성한다.

const toDos = createSlice({
    name: "toDosReducer",
    initialState: [],
    reducers: {
        add: (state, action) => {
            state.push({ text: action.payload, id: Date.now() });
        },
        remove: (state, action) => state.filter(toDo => toDo.id !== action.payload)
    }
}); 

우리는 toDos.Actions로부터 action과 remove라는 actions를 export할 수 있다.

import { createStore } from "redux";
import { createAction, createReducer, configureStore , createSlice} from "@reduxjs/toolkit";

const toDos = createSlice({
    name: "toDosReducer",
    initialState: [],
    reducers: {
        add: (state, action) => {
            state.push({ text: action.payload, id: Date.now() });
        },
        remove: (state, action) => state.filter(toDo => toDo.id !== action.payload)
    }
});

export const { add, remove } = toDos.actions;

export default configureStore({ reducer: toDos.reducer });

console.log(toDos.reducer);를 하면 state, action을 출력해볼 수 있다.

마지막으로 변한 코드 때문에 다른 코드를 수정해야한다.

Home.js로가서

import { actionCreators } from "../store";
->  import { add } from "../store";


addToDo: text => dispatch(actionCreators.addToDo(text))
->  addToDo: text => dispatch(add(text))

로 수정한다. 그리고 ToDo.js로 가서

import { actionCreators } from "../store";
-> import { remove } from "../store";


onBtnClick: () => dispatch(actionCreators.deleteToDo(ownProps.id))
-> onBtnClick: () => dispatch(remove(ownProps.id))

로 수정해준다.

 

#4.5 Conclusions

처음 길었던 코드를 다양한 방법으로 줄여보았다.createAcion, createReducer(switch 대신 사용) , Redux Developer Tools(action, state 상태를 확인함), createSlice를 사용했다. redux를 사용하는 다양한 방법을 해보았다.

 

-끝-

반응형