✍️ What I Learned/TIL

[TIL] Redux toolkit - createAction, createReducer, configureStore, createSlice

2023. 8. 1. 21:10
목차
  1. 1. createAction + reducer
  2. 2. createAction + createReducer
  3. RTK 2.0.0부터 createReducer 대신 builder callback 기반으로 변경
  4. 3. configureStore
  5. 4. createSlice


1. createAction + reducer

  • rtk의 createAction 함수를 사용하여 action creator 정의
  • createAction 함수는 자동으로 action creator 함수를 생성하여 action object를 생성한다.
    • (ex. { type: 'ADD', payload: actionPayload })
  • 그 후 reducer 함수를 직접 정의하여, action type과 payload를 기반으로 상태가 어떻게 업데이트되는지를 지정
  • state가 변화하면 state를 직접 변경하지 않고, reducer 함수에서 새로운 state를 생성하여 반환

 

 


2. createAction + createReducer

  • rtk의 createAction 및 createReducer 함수를 모두 사용한다.
  • createAction 함수는 1번 방법과 마찬가지로 action creator를 정의하는데 사용
  • createReducer 함수는 reducer를 보다 간결하게 정의하고, action type에 따라 state 업데이트를 자동으로 처리하는 reducer 함수를 생성한다.
  • state를 직접 수정해도 immer의 존재 때문에 상태의 불변성이 유지되며, 새로운 state로 반환할 필요가 없음

 

RTK 2.0.0부터 createReducer 대신 builder callback 기반으로 변경

createReducer를 사용하면 콘솔에 아래와 같은 경고메시지가 발생한다.
bundle.js:1712 The object notation for createReducer is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer
import shortid from "shortid";
import { createStore } from "redux";
import { createReducer, createAction, PayloadAction } from "@reduxjs/toolkit";

export type RootState = {
  todos: Todo[];
};

export type Todo = {
  id: string;
  text: string;
}

const ADD = "ADD";
const DELETE = "DELETE";

type AddAction = PayloadAction<string, typeof ADD>;
type DeleteAction = PayloadAction<string, typeof DELETE>;
type ActionType = AddAction | DeleteAction;

// createAction
export const addTodo = createAction<string>(ADD);
export const deleteTodo = createAction<string>(DELETE);

const initialState: RootState = {
  todos: [
    {
      id: shortid(),
      text: "리액트 공부하기"
    },
    {
      id: shortid(),
      text: "밥먹기",
    }
  ]
}

// redux-toolkit: createAction, createReducer with builder callback
const reducer = createReducer(initialState, (builder) => {
  builder
    .addCase(addTodo, (state, action: ActionType) => {
      state.todos.push({ text: action.payload, id: shortid() });
    })
    .addCase(deleteTodo, (state, action: ActionType) => {
      state.todos = state.todos.filter(todo => todo.id !== action.payload);
    });
});

const store = createStore(reducer);

export default store;

 

 


3. configureStore

  • 기존 createStore 함수보다 store 생성을 더 간편하게 할 수 있도록 하는 함수
  • middleware와 createStore 함수의 기능을 함께 갖고 있음
  • 기본적으로 Redux devtools 확장 및 Thunk 미들웨어를 포함

 

 


4. createSlice

  • createAction 함수와 createReducer 함수를 각각 사용하여 action과 reducer를 각각 생성할 필요 없이, 한번에 action과 reducer를 생성해주는 함수
import shortid from "shortid";
import { createStore } from "redux";
import { createSlice, configureStore, createReducer, createAction, PayloadAction } from "@reduxjs/toolkit";

export type RootState = {
  todos: Todo[];
};

export type Todo = {
  id: string;
  text: string;
}

const initialState: RootState = {
  todos: [
    {
      id: shortid(),
      text: "리액트 공부하기"
    },
    {
      id: shortid(),
      text: "밥먹기",
    }
  ]
}

// 3. createSlice
const todoSlice = createSlice({
  name: "todosReducer",
  initialState,
  reducers: {
    add: (state, action) => {
      state.todos.push({ text: action.payload, id: shortid() });
    },
    remove: (state, action) => {
      state.todos = state.todos.filter(todo => todo.id !== action.payload);
    }
  }
})

const store = configureStore({
  reducer: todoSlice.reducer
});

export const { add, remove } = todoSlice.actions;
export default store;
저작자표시 (새창열림)

'✍️ What I Learned > TIL' 카테고리의 다른 글

[TIL] useMemo, useCallback  (0) 2023.08.04
[TIL] 온프레미스(On-premise) vs. 클라우드(Cloud), AWS 소개, AWS의 주요 서비스  (0) 2023.08.02
[TIL] 중첩 라우팅(Nested Routes) (feat. React-Router-DOM v6)  (0) 2023.07.31
[TIL] TypeScript로 투두리스트 만들기 - global.d.ts, 이벤트 타입지정  (0) 2023.07.28
[TIL] TypeScript + React 개발환경 세팅  (0) 2023.07.27
  1. 1. createAction + reducer
  2. 2. createAction + createReducer
  3. RTK 2.0.0부터 createReducer 대신 builder callback 기반으로 변경
  4. 3. configureStore
  5. 4. createSlice
'✍️ What I Learned/TIL' 카테고리의 다른 글
  • [TIL] useMemo, useCallback
  • [TIL] 온프레미스(On-premise) vs. 클라우드(Cloud), AWS 소개, AWS의 주요 서비스
  • [TIL] 중첩 라우팅(Nested Routes) (feat. React-Router-DOM v6)
  • [TIL] TypeScript로 투두리스트 만들기 - global.d.ts, 이벤트 타입지정
Jiwon()
Jiwon()
Jiwon()
jiwondev.log
Jiwon()
전체
오늘
어제
  • 전체보기 (86)
    • ✍️ What I Learned (52)
      • TIL (41)
      • 트러블슈팅 (8)
    • 💻 Programming (31)
      • Algorithm (12)
      • React (1)
      • JS, TS (7)
      • HTML, CSS (7)
      • 기타 (4)
    • 🖊️ 일기 (3)
      • 일상기록 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Redux
  • slice
  • 자바스크립트
  • Prisma
  • javascript
  • 프론트엔드
  • 클린코드
  • Next.js
  • 알고리즘
  • 프로그래머스
  • 타입스크립트
  • transition
  • css
  • reduxtoolkit
  • React-Hook-Form
  • 웹개발
  • 리액트
  • nextjs
  • tailwindcss
  • ChatGPT
  • HTML
  • 코딩
  • 내일배움캠프
  • 트러블슈팅
  • SSR
  • Til
  • Firebase
  • recoil
  • TypeScript
  • React

최근 댓글

최근 글

hELLO · Designed By 정상우.
Jiwon()
[TIL] Redux toolkit - createAction, createReducer, configureStore, createSlice
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.