Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

redux toolkit 본문

React

redux toolkit

혜won 2023. 11. 28. 20:26

리덕스 툴킷이란?

기존의 리덕스를 더욱 간결하고 편하게 쓸 수 있게 만든 것이다. 

 

장점 

1. action value, actioncreator, reducer를 하나에 해결할 수있다.

redux

기존의 순수?리덕스에서는 Ducks 패턴을 참고하여 reducer, action Value, action creator를 따로 작성해주었다. 

2023.11.10 - [React] - Redux

 

Redux

redux는 상태 관리 라이브러리라고 하는데 redux는 왜 필요한가. 장점이 3가지가 있는데 1. 리덕스를 사용하면State를 공유하고자 할때 부-모 관계가 아니여도 된다 2. 중간에 의미없이 컴포넌트를 거

hyewonjung-coding.tistory.com

import React from "react";
import { v4 as uuidv4 } from "uuid";

// action value
const ADD_TODO = "ADD_TODO";
const REMOVE_TODO = "REMOVE_TODO";
const SWITCH_TODO = "SWITCH_TODO";
//action creator
export const addTodo = (payload) => {
  return {
    type: ADD_TODO,
    payload,
  };
};

export const removeTodo = (payload) => {
  return {
    type: REMOVE_TODO,
    payload,
  };
};

export const switchTodo = (payload) => {
  return {
    type: SWITCH_TODO,
    payload,
  };
};

// initial states
const initialState = [
  {
    id: uuidv4(),
    title: "리액트 공부하기",
    contents: "빨리빨리 암기하기",
    isDone: false,
  },
  {
    id: uuidv4(),
    title: "스프링 공부하기",
    contents: "인강 열심히 들어보기!!",
    isDone: true,
  },
  {
    id: uuidv4(),
    title: "데이트",
    contents: "홍대입구역에서 3시까지",
    isDone: false,
  },
];

// reducers
const todos = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO: // 기존의 배열에 입력받은 객체를 더함
      return [...state, action.payload];
    case REMOVE_TODO: // 기존의 배열에서 입력받은 id의 객체를 제거(filter)
      return state.filter((item) => item.id !== action.payload);
    case SWITCH_TODO: // 기존의 배열에서 입력받은 id에 해당하는 것만 isDone을 반대로 변경(아니면 그대로 반환)
      return state.map((item) => {
        if (item.id === action.payload) {
          return { ...item, isDone: !item.isDone };
        } else {
          return item;
        }
      });
    default:
      return state;
  }
};

// export
export default todos;

redux toolkit

redux  toolkit은 따로 적을 필요 없이 createSilce를 이용해서 이름, 초기값, reducers를 넣어주면 된다. 

createSlice는 객체를 받고 그 안에 reducers는 value로 객체를 받아 안에 reducer를 받는다. 

import { createSlice } from "@reduxjs/toolkit";
import React from "react";
import { v4 as uuidv4 } from "uuid";


const initialState = [
  {
    id: uuidv4(),
    title: "리액트 공부하기",
    contents: "빨리빨리 암기하기",
    isDone: false,
  },
  {
    id: uuidv4(),
    title: "스프링 공부하기",
    contents: "인강 열심히 들어보기!!",
    isDone: true,
  },
  {
    id: uuidv4(),
    title: "데이트",
    contents: "홍대입구역에서 3시까지",
    isDone: false,
  },
];

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    addTodo: (state, action) => {
      // return [...state, action.payload];
      //toolkit의 장점 불변성 유지를 안 해도 된다.
      //왜? tollkit 자체에 immer라는 기능이 있기때문이다. 
      state.push(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;

2. 불변성 유지를 안해도 된다. 

기존의 리덕스에서는 불변성을 유지해야만 리액트가 읽을 수 있기에 push 메소드는 사용할 수 없었는데  리덕스 툴킷은 툴킷 자체가 가지고 있는 immer라는 기능이 있어서 push 메소드를 사용해도 state의 변화를 알아차릴 수 있다.

 

3. store가 간결해진다

redux

import { createStore } from "redux";
import { combineReducers } from "redux";
import todos from "../modules/todos";

const rootReducer = combineReducers({
  todos,
});

const store = createStore(rootReducer);

export default store;

redux toolkit

import todos from "../modules/todos";

const { configureStore } = require("@reduxjs/toolkit");

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

export default store;

 

'React' 카테고리의 다른 글

json server  (0) 2023.11.29
axios get post delete patch  (0) 2023.11.29
React router dom  (0) 2023.11.13
children 활용하기  (0) 2023.11.13
redux payload, Ducks  (1) 2023.11.12