๐ŸŽˆRedux + React(with Redux Toolkit)

aspalt85ยท2021๋…„ 2์›” 25์ผ
0
post-thumbnail

๐Ÿ“ƒ store.js

๐Ÿ“Œ createAction + createReducer

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

  const addToDo = createAction("ADD");

  const deleteToDo = createAction("DELETE");

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

// const store = createStore(reducer);
const store = configureStore({ reducer: toDos.reducer });
// configureStore์€ middleware(Redux Dev Tool)์™€ ํ•จ๊ป˜ store๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

export const actionCreators = {
  addToDo,
  deleteToDo
};
export default store;

๐Ÿ“‹ Memo

Redux Toolkit์„ ์‚ฌ์šฉํ•˜๋ฉด state๋ฅผ mutateํ•ด๋„ ๋œ๋‹ค. immer.js์™€ ๊ฐ™์ด ์ž‘๋™ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
createReducer์„ ํ•  ๋•Œ์—๋Š” 2๊ฐ€์ง€ ์˜ต์…˜์ด ์žˆ๋‹ค.
1. ์ƒˆ๋กœ์šด state๋ฅผ returnํ•  ์ˆ˜ ์žˆ๋‹ค => [{ text: action.payload, id: Date.now() }, ...state]
2. state ์ž์ฒด๋ฅผ mutateํ•  ์ˆ˜ ์žˆ๋‹ค. => state.push({ text: action.payload, id: Date.now() }) ํ•˜์ง€๋งŒ ๋‚ด๋ถ€์ ์œผ๋กœ 1๋ฒˆ๊ณผ ๊ฐ™์€ ์ž‘์—…์ด ์ด๋ฃจ์–ด์ง€๊ณ  ์žˆ๋‹ค.

๐Ÿ“Œ createSlice

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

const toDos = createSlice({
  name: "toDoReducer",
  initialState: [],
  reducers: {
    add: (state, action) => {
      state.push({ text: action.payload, id: Date.now() });
    },
    remove: (state, action) => {
      return state.filter((toDo) => toDo.id !== action.payload);
    },
  },
});
// const store = createStore(reducer);
const store = configureStore({ reducer: toDos.reducer });
// configureStore์€ middleware(Redux Dev Tool)์™€ ํ•จ๊ป˜ store๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

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

๐Ÿ“‹ Memo

createSlice()๋Š” internally createAction, createReducer์„ ์‚ฌ์šฉํ•œ๋‹ค.
reducers: {}์—์„œ ์ž๋™์œผ๋กœ action์„ ์ƒ์„ฑํ•œ๋‹ค.

profile
https://github.com/Coaspe

0๊ฐœ์˜ ๋Œ“๊ธ€