mediumReact Native#13

Redux Toolkit slice

Prompt

Create a Redux Toolkit slice for a counter with actions: increment, decrement, incrementByAmount. Wrap a component with the Redux Provider and display the count.

Solution

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1 },
    decrement: (state) => { state.value -= 1 },
    incrementByAmount: (state, action) => { state.value += action.payload },
  },
})
const store = configureStore({ reducer: { counter: counterSlice.reducer } })
// Use: <Provider store={store}><Counter /></Provider>
// In component: useSelector(s => s.counter.value) + useDispatch
Mentor's take

Redux Toolkit is the official answer to Redux's boilerplate reputation: createSlice generates the action types, action creators, and reducer from one declaration, and configureStore wires the devtools and default middleware (including the checks that catch accidental state mutation and non-serializable values in dev).

The line interviewers probe: state.value += 1 looks like mutation but isn't. Slice reducers run inside Immerstate is a draft proxy, and Immer converts your imperative changes into an immutable update with structural sharing. So the reference-equality contract Redux depends on still holds; you just stop hand-writing nested spreads. Say "Immer draft," not "RTK lets you mutate" — the first is precise, the second is wrong in a way a senior interviewer will catch.

Component wiring follows the same subscription economics as any store: useSelector(s => s.counter.value) re-renders only when that selected value changes, so select the narrowest slice you need; useDispatch plus the generated action creators (counterSlice.actions.increment()) replaces hand-typed action objects.

Red flag: hand-writing action type constants and switch-statement reducers in 2026, or claiming RTK "made Redux mutable." Both date your Redux to pre-Toolkit.

Say it: "createSlice generates actions and reducer from one declaration, and the 'mutations' are Immer drafts compiled to immutable updates — Redux's reference-equality model is intact, only the ceremony is gone."