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).
Pitfall 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;.