Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 71 ยท Projects

Project: Shopping App

Build a React Native shopping app: product list, cart reducer and context, bottom tabs with a badge and a validated checkout form, with a runnable cart stand-in.

Shopping apps are a good test of whether you can share state across screens. The product list needs to add items, the cart tab needs to show them and their total, the tab icon needs a badge with the item count, and the checkout form needs to read the cart one last time before sending the order. All four places must agree at every moment, so the cart lives in one shared place.

In this project you build the cart as a reducer, expose it with React context, show it in a tab navigator and finish with a checkout form that validates before it submits. Related lessons: Tab and Drawer Navigators, Global State with Zustand and Redux Toolkit and Forms and Validation.

What runs on this site. Native tabs and FlatList need a native runtime, so the real screens are read-only. The runnable examples are stand-ins: the cart reducer and price helpers are real JavaScript, and the app is drawn with HTML, with tabs implemented by a plain state variable. No payment happens anywhere; "Place order" only prints a summary, and prices are invented sample data.

Plan the app

Three tabs

Shop Browse and add products.
Cart Quantities, totals, checkout.
Profile Optional, not built here.

The Cart tab shows a badge with the item count.

1 / 2

Money is not a float

The first rule of a shop: store prices as integer cents. In JavaScript 0.1 + 0.2 is 0.30000000000000004, and that kind of error becomes visible when you sum a cart. Keep priceCents: 1999, do all arithmetic on integers, and only format at the edge when displaying.

JavaScript
export function formatPrice(cents, currency = 'USD', locale = 'en-US') {
  return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100);
}

Intl.NumberFormat is available in Hermes and gives the right symbol and separators for the locale. For a real store, prices and totals must be recomputed on your server at order time; the app total is only a preview.

The cart reducer

The cart is a map from product id to quantity. Using a map (or an array of lines) with a single reducer makes the rules explicit: adding an existing product increments the quantity, and reducing to zero removes the line.

JavaScript
export function cartReducer(state, action) {
  switch (action.type) {
    case 'add': {
      const qty = (state[action.id] ?? 0) + 1;
      return { ...state, [action.id]: qty };
    }
    case 'decrement': {
      const qty = (state[action.id] ?? 0) - 1;
      if (qty <= 0) {
        const { [action.id]: _removed, ...rest } = state;
        return rest;
      }
      return { ...state, [action.id]: qty };
    }
    case 'remove': {
      const { [action.id]: _removed, ...rest } = state;
      return rest;
    }
    case 'clear':
      return {};
    default:
      return state;
  }
}

export function cartLines(state, products) {
  return Object.entries(state).flatMap(([id, quantity]) => {
    const product = products.find((p) => p.id === id);
    return product ? [{ product, quantity, lineCents: product.priceCents * quantity }] : [];
  });
}

export const cartCount = (state) => Object.values(state).reduce((sum, q) => sum + q, 0);
export const cartTotal = (lines) => lines.reduce((sum, l) => sum + l.lineCents, 0);

Notice that the cart stores only ids and quantities, not copies of products. The names and prices are looked up in the catalog each time, so a price change in the catalog is reflected everywhere. cartLines quietly drops ids that no longer exist in the catalog, which protects you if an old saved cart refers to a product that was withdrawn.

Cart reducer and totals

Sharing the cart with context

Context lets any component below the provider read the cart without prop drilling through the navigator. Put the provider above the navigation container, because tab screens are children of it.

JSX
import { createContext, useContext, useMemo, useReducer } from 'react';
import { cartReducer, cartCount, cartLines, cartTotal } from './cart';
import { products } from './catalog';

const CartContext = createContext(null);

export function CartProvider({ children }) {
  const [items, dispatch] = useReducer(cartReducer, {});
  const value = useMemo(() => {
    const lines = cartLines(items, products);
    return { lines, count: cartCount(items), totalCents: cartTotal(lines), dispatch };
  }, [items]);
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

export function useCart() {
  const ctx = useContext(CartContext);
  if (!ctx) throw new Error('useCart must be used inside CartProvider');
  return ctx;
}

The useMemo keeps the context value stable until the cart really changes, so consumers do not re-render for unrelated reasons. For bigger apps a store with selectors (Zustand) avoids re-rendering every consumer when only the count changed, but for a cart this size, context is plenty.

Tabs with a badge

With React Navigation, the bottom tab navigator reads the count through the same hook:

JSX
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

function Tabs() {
  const { count } = useCart();
  return (
    <Tab.Navigator>
      <Tab.Screen name="Shop" component={ShopScreen} />
      <Tab.Screen
        name="Cart"
        component={CartScreen}
        options={{ tabBarBadge: count > 0 ? count : undefined }}
      />
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <CartProvider>
      <NavigationContainer>
        <Tabs />
      </NavigationContainer>
    </CartProvider>
  );
}

Passing undefined to tabBarBadge hides the badge when the cart is empty. The Shop screen is a FlatList with two columns (numColumns={2}), each card showing the name, the formatted price and an Add button that calls dispatch({ type: 'add', id }). A real app would put a stack inside each tab so a product can open a detail page.

Checkout form

The checkout validates before it submits, and it validates in a pure function so the rules are testable and the screen only shows messages.

JavaScript
export function validateCheckout(form) {
  const errors = {};
  if (form.name.trim().length < 2) errors.name = 'Enter your full name.';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) errors.email = 'Enter a valid email.';
  if (form.postal.trim().length < 4) errors.postal = 'Enter a postal code.';
  return errors;
}

The email pattern is intentionally forgiving: its job is to catch typos such as a missing @, not to prove the address exists. Real validation happens when you send a confirmation message. In the screen, each TextInput gets the next field wired with returnKeyType="next" and a ref, the email field uses keyboardType="email-address" with autoCapitalize="none", and error text appears under a field only after the user tried to submit.

Shopping app with tabs, cart context and checkout (stand-in)

Notice that switching tabs does not lose the cart: the provider sits above the tab switch. The error messages appear only after the first attempt, which keeps a fresh form from shouting at the user before they type anything.

Production checklist

  • Never trust the app's total. The server recomputes prices and stock when the order arrives.
  • Use a payments SDK. Card details must go through your payment provider's components, never through your own text inputs and never through your server logs.
  • Persist the cart (see Storing Data: AsyncStorage, MMKV and SecureStore) and handle products that vanished.
  • Handle slow networks: disable the Place order button while submitting so a double tap cannot create two orders.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the cart store product ids and quantities instead of copies of products?

    Storing ids keeps one source of truth for product data. If a price changes in the catalog, the cart reflects it automatically.
  2. 2. Why are prices stored as integer cents?

    Binary floating point cannot represent many decimal fractions exactly. Integer cents keep arithmetic exact; you convert to a formatted string only when displaying.
  3. 3. Where must the CartProvider be placed so the tab bar badge and every screen can read the cart?

    Context is available to components below the provider. Putting it above the NavigationContainer makes it available to every tab, header and screen.
  4. 4. A user taps Place order with an empty form. What should the form do?

    Validation runs first. Errors are shown (after the first submit attempt) and the order is not placed until the form is valid.

Summary

  • Keep prices as integer cents, format them with Intl.NumberFormat, and recompute totals on the server.
  • A cart reducer over { productId: quantity } plus derived helpers (cartLines, cartCount, cartTotal) keeps the rules in one place.
  • A context provider above the navigator shares the cart with the product list, the tab badge, the cart screen and checkout.
  • Validate the checkout with a pure function, show errors after the first submit, and never handle card data yourself.
  • On this site the native tabs and lists are read-only; the cart logic and a tabbed stand-in run for real.

Next, build a conversation screen in Project: Chat App UI.