← Back to React, page 4

react-0072 · Medium mid

What is Redux Toolkit, how do slices, the store and hooks fit together, and why is it preferred over classic Redux?

Redux Toolkit (RTK) is the official, standard way to write Redux. createSlice defines state, reducers and generated actions in one place, and lets you write updates that look like mutations because Immer turns them into immutable updates. configureStore builds the store with good defaults and devtools. Components use useSelector to read state and useDispatch to send actions, inside a Provider.

Full answer

Classic Redux needed action type constants, action creators, switch-based reducers and careful immutable updates, all in separate files. Redux Toolkit removes that ceremony while keeping Redux's single store, predictable updates and strong devtools.

createSlice({ name, initialState, reducers }) creates the pieces for one feature. Each reducer function receives the state and the action. Inside it you may write state.items.push(item), because Immer records the changes and produces a new immutable state. The slice returns the reducer and an actions object with a ready action creator for each reducer. The action type string is generated from the slice name and the reducer name.

configureStore({ reducer: { cart: cartSlice.reducer } }) combines slices, adds the Redux DevTools hookup and middleware that detects accidental mutation and non-serializable values in development.

In React, wrap the app in <Provider store={store}> from react-redux. Read state with useSelector((state) => state.cart.items.length). The component re-renders only when the selected value changes, so select the smallest piece you need. Send actions with useDispatch().

For async work, createAsyncThunk handles pending, fulfilled and rejected states, and listener middleware handles side effects. For server data, RTK Query (see its own question) is usually better than hand-written thunks.

When to choose RTK: large apps and teams that want conventions, middleware, time-travel debugging and a clear data flow. For small apps, useState, context or Zustand may be lighter.

The example keeps a shopping cart in a slice.

jsx
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useDispatch, useSelector } from 'react-redux';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: {
    added(state, action) {
      state.items.push(action.payload);
    },
    cleared(state) {
      state.items = [];
    },
  },
});

const { added, cleared } = cartSlice.actions;
const store = configureStore({ reducer: { cart: cartSlice.reducer } });

function Cart() {
  const items = useSelector((state) => state.cart.items);
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch(added('Pen'))}>Add pen</button>
      <button onClick={() => dispatch(cleared())}>Clear</button>
      <p>
        {items.length} items: {items.join(', ')}
      </p>
    </div>
  );
}

export default function App() {
  return (
    <Provider store={store}>
      <Cart />
    </Provider>
  );
}

The reducers look like they mutate state, but Immer produces new immutable state. The check pressed Add pen and then Clear, so the cart ends empty. Rendered result: <div><button>Add pen</button><button>Clear</button><p>0 items: </p></div>

Key points

  • createSlice produces reducers and action creators together. Immer lets you write mutating-style updates safely.
  • configureStore sets up the store, devtools and development checks.
  • Provider supplies the store. useSelector reads, useDispatch writes.
  • Select the smallest value you need to limit re-renders.
  • Use RTK Query for server data and thunks or listeners for other async work.

Common mistakes

  • Mutating state outside a slice reducer, where Immer does not protect you.
  • Selecting the whole state in useSelector and re-rendering on every change.
  • Returning a new value and mutating the draft in the same reducer.
  • Putting non-serializable values such as class instances in the store.
  • Using Redux for state that useState would handle.

Follow-ups

  • What does Immer do inside createSlice reducers?
  • How does createAsyncThunk model loading and error states?
  • When would you pick Zustand instead of Redux Toolkit?

Tips

  • Contrast with classic Redux boilerplate. It shows you know the history.
  • Explain the Immer point carefully. Many candidates say "RTK allows mutation".
  • Say what you would put in Redux and what you would leave out.