Redux Tookit๐Ÿ“‘

  • ๊ธฐ์กด์˜ Redux ์ฝ”๋“œ๋ฅผ ์กฐ๊ธˆ ๋” ๊ฐ„์†Œํ™” ํ•  ์ˆ˜ ์žˆ์Œ

  • Redux ์™ธ์— ์„ค์น˜ํ•ด์•ผ ํ–ˆ๋˜ ๊ฐ์ข… ํŒจํ‚ค์ง€ ๊ธฐ๋Šฅ์„ ๋‚ด์žฅํ•˜๊ณ  ์žˆ์–ด, ๋” ๊ฐ„ํŽธํ•˜๊ฒŒ ๋‹ค์–‘ํ•œ ํŒจํ‚ค์ง€ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์›€

  • $ yarn add @reduxjs/toolkit react-redux

๐Ÿงกreducer ์ƒ์„ฑ

โœจ๊ธฐ์กด reducer์ƒ์„ฑ๋ฐฉ์‹

  • ์ฝ”๋“œ ์˜ค๋ฅ˜๋ฐฉ์ง€์™€ ๊ฐ€๋…์„ฑ ํ–ฅ์ƒ์„ ์œ„ํ•ด ์•ก์…˜ํƒ€์ž…๊ณผ, ์•ก์…˜๊ฐ์ฒด์ƒ์„ฑํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ์ •์˜ํ•œ ๋’ค ๋ฆฌ๋“€์„œ์— ์ ์šฉํ•˜์˜€์Œ

๊ธฐ์กด Reducer์ƒ์„ฑ๋ฐฉ์‹

//์•ก์…˜ํƒ€์ž…์ƒ์„ฑ
export const INC_COUNT = 'counter/INC_COUNT'

//์•ก์…˜์ƒ์„ฑํ•จ์ˆ˜
const increase = () => {
  return {
    type: INC_COUNT,
  }
}

//์ดˆ๊ธฐ๊ฐ’
const initialState = 0

//๋ฆฌ๋“€์„œ
export default function couter(state = initialState, action) {
  switch (action.type) {
    case INC:
      return state + 1
  }
}

โœจtoolkit์œผ๋กœ reducer์ƒ์„ฑ ๊ฐ„์†Œํ™”

  • ์•ก์…˜ํƒ€์ž…์ง€์ •๋ณ€์ˆ˜์™€ ์•ก์…˜๊ฐ์ฒด์ƒ์„ฑํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•˜์ง€ ์•Š๊ณ  createAction์œผ๋กœ ์กฐ๊ธˆ ๋” ๊ฐ„ํŽธํ•˜๊ฒŒ action์„ ์ •์˜
  • createReducer๋กœ switch๋ฌธ์„ ์‚ฌ์šฉํ•  ํ•„์š” ์—†์ด ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ž‘์„ฑ

toolkit์„ ํ™œ์šฉํ•œ Reducer์ƒ์„ฑ๋ฐฉ์‹

import { createAction, createReducer } from "@reduxjs/toolkit";

// ์•ก์…˜์ƒ์„ฑ
export const increase = createAction('counter/increase')

//์ดˆ๊ธฐ๊ฐ’
const initialState = 0

//๋ฆฌ๋“€์„œ
const counter = createReducer(initialState, {
	[increase] : (state,action) => state + 1
})

export default counter

๐ŸงกStore ์ƒ์„ฑ

  • ๊ธฐ์กด์˜ createStore๊ฐ€ ์•„๋‹Œ configureStore๋กœ store๋ฅผ ์ƒ์„ฑ
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer'

const store = configureStore({
  reducer: counterReducer
})
  • store๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ์ผ ๋•Œ ๊ธฐ์กด๋ฐฉ์‹๊ณผ ๊ฐ™์ด combineReducers์‚ฌ์šฉ
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer'
import postReducer from './postReducer'

const rootReducer = combineReducers({
  counter: counterReducer,
  post: postReducer
})

const store = configureStore({
  reducer: rootReducer
})

๐ŸงกSlice

  • createAction๊ณผ createReducer๋ฅผ ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋กœ ํ†ตํ•ฉํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹
  • ์Šฌ๋ผ์ด์Šค ์ด๋ฆ„.actions , ์Šฌ๋ผ์ด์Šค ์ด๋ฆ„.reducers์œผ๋กœ ๊ฐ ์•ก์…˜๋“ค๊ณผ ๋ฆฌ๋“€์„œ๋ฅผ ๊บผ๋‚ด์˜ฌ ์ˆ˜ ์žˆ๋‹ค
//counterSlice.js
import { createSlice } from "@reduxjs/toolkit";

const initialState = 0;

counterSlice = createSlice({
  name: counter,
  initialState,
  reducers: {
    increase: (state) => state + 1,
    decrease: (state) => state - 1,
  }
})

export const { increase, decrease } = counterSlice.actions;
export default counterSlice.reducer;
//store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice'

const store = configureStore({
  reducer: counterReducer
})
profile
ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์ผ๊ธฐ ๐Ÿ’ญ

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