createSlice gộp actions, action types, và reducer vào một chỗ — Immer bên trong cho phép viết mutable syntax mà vẫn immutable thật sự. createSlice là API quan trọng nhất của RTK, nhận object gồm name (prefix cho action types), initialState, và reducers (object chứa các reducer functions).
- Nó tự động tạo action creators và action types — ví dụ: reducer
incrementtrong slice tên 'counter' tạo ra action typecounter/incrementvà action creatorcounterSlice.actions.increment(). - Bên trong dùng Immer nên viết
state.value += 1thay vìreturn { ...state, value: state.value + 1 }— code ngắn hơn 3-4 lần với nested state. - Export 2 thứ:
counterSlice.actions(dùng trong component dispatch) vàcounterSlice.reducer(dùng trong configureStore). - Lưu ý thường gặp: trong reducers của createSlice, hoặc mutate state HOẶC return state mới, KHÔNG làm cả hai — Immer sẽ throw error.
Ví dụ sai: state.items.push(item); return state;.
createSlice combines actions, action types, and reducer in one place — Immer internally allows mutable write syntax while remaining truly immutable. createSlice is the most important API in RTK.
- It accepts an object with
name(prefix for action types),initialState, andreducers(an object of reducer functions). - It automatically generates action creators and action types — for example, a reducer named
incrementin a slice called 'counter' produces action typecounter/incrementand action creatorcounterSlice.actions.increment(). - Immer is used internally, so you can write
state.value += 1instead ofreturn { ...state, value: state.value + 1 }— 3-4x less code for nested state. - Export two things:
counterSlice.actions(used in components to dispatch) andcounterSlice.reducer(used in configureStore). - Common pitfall: inside createSlice reducers, either mutate state OR return a new state — never both.
- Immer will throw an error.
- Wrong example:
state.items.push(item); return state;