Redux Toolkit

July 28, 2021 · 4 mins read label-icon Redux

Redux Toolkit (RTK)

  • ๊ธฐ์กด์˜ Redux ๋ฅผ ๋”์šฑ ์‰ฝ๊ณ  ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” Redux ๊ณต์‹ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
  • Redux DevTools Extension ๊ณผ Redux middleware(thunk, logger), immer ๋“ฑ์˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ๊ธฐ๋ณธ์œผ๋กœ ํฌํ•จ๋˜์–ด ์žˆ๋‹ค.

์ฃผ์š” ํ•จ์ˆ˜

configureStore

  • createStore ๋ฅผ ๋žฉํ•‘ํ•˜์—ฌ ๊ธฐ์กด์˜ createStore ์—ญํ• ์„ ํ•œ๋‹ค.
  • ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด Redux DevTools Extension ๊ณผ Redux middleware ๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.
1
2
3
4
5
6
7
8
// Before
const store = createStore(counter)

// After
const store = configureStore({
  reducer: counter,
  //middleware: [thunk, logger]
})

createAction

  • ์•ก์…˜ ํƒ€์ž… ๋ฌธ์ž์—ด์„ ์ธ์ž๋กœ ๋ฐ›๊ณ , ํ•ด๋‹น ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋Š” ์•ก์…˜ ์ƒ์„ฑ์žํ•จ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Before
const INCREMENT = 'INCREMENT'

function incrementOriginal() {
  return { type: INCREMENT }
}
console.log(incrementOriginal()) // {type: "INCREMENT"}


// After
const incrementNew = createAction('INCREMENT')

console.log(incrementNew()) // {type: "INCREMENT"}

createReducer

  • ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ reducer๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜ (Switch ๋ฌธ ์‚ฌ์šฉ x)
  • ๋‚ด์žฅ๋˜์–ด ์žˆ๋Š” immer ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ํ†ตํ•ด ๋ถˆ๋ณ€์„ฑ์„ ์œ ์ง€ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
  • ES6 ์˜ computed ์†์„ฑ์„ ์‚ฌ์šฉํ•˜์—ฌ type๋ฌธ์ž์—ด ๋ณ€์ˆ˜๋กœ ํ‚ค๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ ์ธ์ž๋Š” ์ดˆ๊นƒ๊ฐ’ ๊ฐ์ฒด(initialState), ๋‘ ๋ฒˆ์งธ ์ธ์ž๋Š” reducer ๊ฐ์ฒด๋ฅผ ๋ฐ›๋Š”๋‹ค.
1
2
3
4
5
6
7
8
9
10
11
// Before
function counter(state = 0, action) {
  switch (action.type) {
    case INCREMENT:
      return state + 1
    case DECREMENT:
      return state - 1
    default:
      return state
  }
}
1
2
3
4
5
6
7
8
// After
const increment = createAction('INCREMENT')
const decrement = createAction('DECREMENT')

const counter = createReducer(0, {
  [increment.type]: state => state + 1,
  [decrement]: state => state - 1 // [decrement] == [decrement.type]
})

createSlice

  • action๊ณผ reduder๋ฅผ ํ•ฉ์ณ์„œ ์„ ์–ธํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
1
2
3
4
5
6
7
8
const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
    decrement: state => state - 1
  }
})
1
2
const { actions, reducer } = counterSlice
const { increment, decrement } = actions

์ฐธ๊ณ 

https://redux-toolkit.js.org/
https://soyoung210.github.io/redux-toolkit