Redux Toolkit Setup

1. Install

Example

npm install @reduxjs/toolkit react-redux

2. Create a Slice

A slice holds the initial state and reducers for one feature. Redux Toolkit uses Immer, so you can write "mutating" code safely.

// store/cartSlice.js
import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: {
    addItem: (state, action) => {
      state.items.push(action.payload);      // Immer makes this immutable
    },
    removeItem: (state, action) => {
      state.items = state.items.filter((i) => i.id !== action.payload);
    },
    clearCart: (state) => {
      state.items = [];
    },
  },
});

export const { addItem, removeItem, clearCart } = cartSlice.actions;
export default cartSlice.reducer;

3. Configure the Store and Provider

// store/index.js
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';

export const store = configureStore({
  reducer: { cart: cartReducer },
});

// main.jsx
import { Provider } from 'react-redux';
import { store } from './store';

createRoot(document.getElementById('root')).render(
  <Provider store={store}>
    <App />
  </Provider>
);

4. Use It in Components

import { useSelector, useDispatch } from 'react-redux';
import { addItem, clearCart } from './store/cartSlice';

function Cart() {
  const items = useSelector((state) => state.cart.items);   // read
  const dispatch = useDispatch();                            // write
  return (
    <div>
      <p>{items.length} items</p>
      <button onClick={() => dispatch(addItem({ id: Date.now(), name: 'Pen' }))}>Add</button>
      <button onClick={() => dispatch(clearCart())}>Clear</button>
    </div>
  );
}