본문 바로가기

React

[React] Redux toolkit/ Devtools/ Flux 패턴

TodoList 를 Redux toolkit 으로 리팩토링

 

1. configStore.js

 

const store = configureStore({
  reducer: {
    todos,
  },
});

 

 

2. modules

 

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    addTodo: (state, action) => {
      return [...state, action.payload];
    },
    removeTodo: (state, action) => {
      return state.filter((item) => item.id !== action.payload);
    },
    switchTodo: (state, action) => {
      return state.map((item) => {
        if (item.id === action.payload) {
          return { ...item, isDone: !item.isDone };
        } else {
          return item;
        }
      });
    },
  },
});

export const { addTodo, removeTodo, switchTodo } = todosSlice.actions;
export default todosSlice.reducer;

 

기존의 리덕스는 불변성을 유지해야하기 때문에 새 배열을 만드는 방식을 자주 써왔음

ex) addTodo 할 시, push 를 사용하지 않음. (불변성을 유지하지 않음) 그러나 redux toolikit 안에서는 이런 방식을 사용할 수 있다. 

 

    addTodo: (state, action) => {
      // return [...state, action.payload];
      // redux toolkit 안에 immer 기능이 내장되어 있어 불변성을 유지할 수 있음.
      return state.push(action.payload);
    },

 

Redux Devtools

 

현재 프로젝트의 state 상태, 어떤 액션이 일어났을 때 그 액션이 무엇이고 그것으로 인해 state 가 어떤식으로 변경되었는지 리덕스를 사용하여 개발 할 때 아주 편리하게 사용할 수 있음.

 

구글 웹스토어 플로그인 설치 주소:

https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=ko

 

 

설치하고 리덕스를 사용하는 리액트 프로젝트를 들어가면 이처럼 초록색 불이 들어온다.

 

 

현재 state가 어떤 상태인지 쉽게 알아볼 수 있는 유용한 프로그램이다.

 


 

Flux 패턴

 

Redux 가 나오게 된 배경으로, 다음 자료를 통해 확인 가능

 

https://bestalign.github.io/translation/cartoon-guide-to-flux/

 

Flux로의 카툰 안내서

원문: https://medium.com/code-cartoons/a-cartoon-guide-to-flux-6157355ab207 Flux…

bestalign.github.io

 

https://taegon.kim/archives/5288

 

Flux와 Redux

이 글에서는 Facebook에서 React와 함께 소개한 Flux 아키텍처에 대해 알아보고 Flux를 구현한 Redux 라이브러리를 살펴본 후 이를 적용한 간단한 React 애플리케이션을 작성해보겠다. 본문에 사용된 코

taegon.kim

 

'React' 카테고리의 다른 글

[React] HTTP  (0) 2023.07.04
[React] json-server  (0) 2023.07.04
[React] Redux Toolkit  (0) 2023.07.04
[React] Redux  (0) 2023.06.20
[React] Life Cycle  (0) 2023.06.20