React Native Redux Toolkit

Context API handles small shared data well. Large apps hold much more: shopping carts, user profiles, filters, notifications, and cached lists. Dozens of screens read and change that data. Redux Toolkit keeps all of it in one organized store with strict update rules, which makes behavior predictable and bugs easier to trace.

The Store Idea

Picture a bank vault with one front desk. Customers never open the vault themselves. They fill a request slip, and the clerk updates the records. Redux works the same way.

Screen            Action             Reducer            Store
┌──────┐  dispatch ┌───────────┐  handles ┌─────────┐ saves ┌───────┐
│Button│ ────────► │ addToCart │ ───────► │cartSlice│ ────► │ State │
└──────┘           └───────────┘          └─────────┘       └───┬───┘
    ▲                                                           │
    └──────────────── screen reads updated state ◄──────────────┘

Key Terms

  • Store: the single container for app data
  • Slice: one section of the store, such as cart or user
  • Action: a request describing what happened
  • Reducer: a function that applies the action to the state
  • Dispatch: the act of sending an action

Install the Libraries

npm install @reduxjs/toolkit react-redux

Step 1: Create a Slice

A slice bundles the initial state, the reducers, and the actions of one feature. Redux Toolkit uses a helper that lets you write simple update code safely.

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

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: {
    addItem: (state, action) => {
      state.items.push(action.payload);
    },
    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;

The state.items.push line looks like direct editing. Redux Toolkit watches the change and builds a fresh copy behind the scenes.

Step 2: Configure the Store

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

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

Step 3: Provide the Store

Wrap the app in a Provider so every screen can reach the store.

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

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

Step 4: Read State with useSelector

A selector picks the piece of data a component needs. The component redraws only when that piece changes.

import { useSelector } from 'react-redux';

function CartBadge() {
  const count = useSelector((state) => state.cart.items.length);
  return <Text>Cart ({count})</Text>;
}

Step 5: Send Actions with useDispatch

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

function ProductCard({ product }) {
  const dispatch = useDispatch();

  return (
    <TouchableOpacity onPress={() => dispatch(addItem(product))}>
      <Text>Add {product.name}</Text>
    </TouchableOpacity>
  );
}
ProductCard taps "Add"
        │ dispatch(addItem)
        ▼
     cartSlice updates items
        │
        ▼
CartBadge shows Cart (1)   ← on a different screen

Loading Data with createAsyncThunk

Server requests need loading, success, and failure states. A thunk wraps the request and creates those three stages automatically.

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const fetchProducts = createAsyncThunk('products/fetch', async () => {
  const res = await fetch('https://example.com/products');
  return res.json();
});

const productSlice = createSlice({
  name: 'products',
  initialState: { list: [], status: 'idle' },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchProducts.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchProducts.fulfilled, (state, action) => {
        state.status = 'done';
        state.list = action.payload;
      })
      .addCase(fetchProducts.rejected, (state) => {
        state.status = 'failed';
      });
  },
});

Context or Redux?

Context API              Redux Toolkit
─────────────────        ─────────────────────
Small shared values      Large, complex state
Themes, language         Carts, feeds, caches
No extra library         Extra library, dev tools

Summary

Redux Toolkit manages large app data in one store. Create slices for each feature, configure the store, wrap the app in a Provider, read data with useSelector, and change data with useDispatch. Use createAsyncThunk for server requests and choose Context for smaller needs.