Trung BìnhState Management iconState Management

createSlice trong RTK hoạt động như thế nào?

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 increment trong slice tên 'counter' tạo ra action type counter/increment và action creator counterSlice.actions.increment().
  • Bên trong dùng Immer nên viết state.value += 1 thay 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;.

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management