Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

You can build a useful React store by combining a product catalog, shared cart state, URL routes, a commerce or product API, and a hosted payment handoff. For a learning project, create a Vite client-only app; for a production store that needs search visibility, server data, or custom backend behavior, start with a React framework such as Next.js or React Router. Keep payment-card handling outside your browser code: redirect customers to hosted Stripe Checkout, or use Stripe Checkout Sessions with Elements when you need a branded checkout page. The implementation below takes you from an empty project to a responsive catalog, product details, cart operations, checkout, accessibility checks, and deployment decisions.

What architecture is best for a simple React shop?

Choose the smallest architecture that meets your current requirements. A Vite app is ideal for learning and a client-only prototype. A framework gives you integrated routing and rendering choices when SEO, server-side data, personalization, or a growing codebase matters.

Option Best fit What you must provide Main trade-off
Vite client-only app Prototype, classroom project, small catalog with an external backend Routing, data fetching, API integration, authentication, and deployment services Fastest start, but more decisions remain yours
Next.js or React Router framework Public store where SEO, server data, or future growth is important Framework conventions, server/runtime configuration, and deployment compatible with those features More setup and concepts than a static client
Direct product data Demo with a fixed set of products Reliable pricing, inventory, authentication, order storage, and validation as the project grows Simple initially, but commerce responsibilities quickly become custom work
Commerce API such as Shopify Storefront API Headless storefront that should reuse catalog and cart primitives API credentials, product queries, and a server-side strategy for protected operations Less backend code, but you depend on the API’s model and limits

React’s own guidance says new applications should generally start with a framework, while a from-scratch tool such as Vite remains a practical way to learn the component model. React’s basic unit is the component: split the store into focused pieces that each render and respond to one part of the interface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What do I need before creating the project?

Install Node.js 18 or later. The MDN React tutorial identifies Node 18 as the minimum for Vite 5. You also need a package manager such as npm, a code editor, and a browser with developer tools. Decide whether your first catalog will use local fixture data, a simple JSON endpoint, or a commerce API; that decision affects where pricing and inventory are validated.

Popular on Amazon
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Create a Vite React app

  1. Run
    npm create vite@latest react-store -- --template react
  2. Enter the directory and install dependencies:
    cd react-store
    npm install
  3. Start the development server:
    npm run dev
  4. Open the local address printed by Vite. Keep the terminal running while you edit files.

For a framework project, use that framework’s current starter command instead and keep the same component, state, routing, and checkout boundaries described below. Do not put secret API keys in a Vite environment variable that is exposed to browser bundles; anything shipped to the browser must be treated as public.

How should I model products and render a catalog?

Start with a stable product shape. Give every item an immutable identifier, display title, image URL, price in the smallest currency unit, and optional variant information. Storing cents (or the smallest unit for the selected currency) as an integer avoids most floating-point display errors.

const products = [
  {
    id: 'mug-001',
    title: 'Stoneware Mug',
    image: '/images/mug.jpg',
    price: 2400,
    currency: 'USD',
    variants: [{ id: 'blue', name: 'Blue' }, { id: 'cream', name: 'Cream' }]
  },
  {
    id: 'notebook-001',
    title: 'Grid Notebook',
    image: '/images/notebook.jpg',
    price: 1200,
    currency: 'USD'
  }
];

Use a reusable ProductCard so a grid and a search result list share the same price, image, and add-to-cart behavior. React’s list rendering requires a stable key; use the product or variant ID rather than an array index.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function ProductCard({ product, onAdd }) {
  return (
    <article className='product-card'>
      <img src={product.image} alt={product.title} />
      <h3>{product.title}</h3>
      <p>{new Intl.NumberFormat('en-US', {
        style: 'currency', currency: product.currency
      }).format(product.price / 100)}</p>
      <button type='button' onClick={() => onAdd(product)}>
        Add to cart
      </button>
    </article>
  );
}

function ProductGrid({ products, onAdd }) {
  return (
    <section aria-labelledby='catalog-heading'>
      <h2 id='catalog-heading'>Products</h2>
      <div className='product-grid'>
        {products.map(product => (
          <ProductCard key={product.id} product={product} onAdd={onAdd} />
        ))}
      </div>
    </section>
  );
}

When products come from an API, normalize the response into this shape at the boundary. That keeps presentation components independent of whether the backend calls a field title, name, or something else.

How do I build a shopping cart with shared React state?

The cart must be available to the catalog, product page, header badge, and cart route. Put its state in a provider (or a dedicated state store) above those components. Support adding an item, removing an item, changing quantity, clearing the cart, calculating a subtotal, and rendering an explicit empty state.

Also popular on Amazon
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import { createContext, useContext, useMemo, useReducer } from 'react';

const CartContext = createContext(null);

function reducer(state, action) {
  switch (action.type) {
    case 'add': {
      const existing = state.find(item =>
        item.id === action.product.id && item.variantId === action.variantId
      );
      if (existing) {
        return state.map(item => item === existing
          ? { ...item, quantity: item.quantity + 1 }
          : item
        );
      }
      return [...state, {
        id: action.product.id,
        title: action.product.title,
        price: action.product.price,
        image: action.product.image,
        variantId: action.variantId || null,
        quantity: 1
      }];
    }
    case 'setQuantity':
      return state
        .map(item => item.id === action.id
          ? { ...item, quantity: Math.max(0, action.quantity) }
          : item)
        .filter(item => item.quantity > 0);
    case 'remove':
      return state.filter(item => item.id !== action.id);
    case 'clear':
      return [];
    default:
      return state;
  }
}

export function CartProvider({ children }) {
  const [items, dispatch] = useReducer(reducer, []);
  const subtotal = items.reduce((sum, item) =>
    sum + item.price * item.quantity, 0);
  const value = useMemo(() => ({ items, subtotal, dispatch }), [items, subtotal]);
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

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

Place CartProvider around the router in your entry file. In a real checkout, treat this browser cart as a user interface convenience, not an authority. Recalculate prices, availability, discounts, shipping, and tax on the server or commerce platform before creating an order.

How do I add product, cart, and order-complete routes?

Routing maps URLs to application content and lets you support product parameters such as /products/mug-001. Create routes for the catalog, a product detail page, the cart, and an order-complete page. Keep the completion page separate from the payment return URL so it can explain that payment confirmation is still being verified.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <CartProvider>
        <Routes>
          <Route path='/' element={<CatalogPage />} />
          <Route path='/products/:productId' element={<ProductPage />} />
          <Route path='/cart' element={<CartPage />} />
          <Route path='/order-complete' element={<OrderCompletePage />} />
        </Routes>
      </CartProvider>
    </BrowserRouter>
  );
}

On a product page, read the route parameter, locate the product, and show a not-found state when it does not exist. Add a visible cart link and item count to the shared header. If you deploy a client-side router as static files, configure the host to return the app shell for unknown paths; otherwise a direct visit to a nested URL can produce a server 404.

How should the app fetch products without a fragile loading experience?

Fetch from a stable API or commerce backend rather than scattering requests through individual cards. Track loading, success, empty, and error states explicitly. React’s guidance highlights the complexity of fetching, caching, prefetching, and avoiding request waterfalls; start with one catalog request and add a data library or framework data layer when those concerns become significant.

function CatalogPage() {
  const [state, setState] = useState({ status: 'loading', products: [], error: null });

  useEffect(() => {
    const controller = new AbortController();
    fetch('/api/products', { signal: controller.signal })
      .then(response => {
        if (!response.ok) throw new Error('Catalog request failed');
        return response.json();
      })
      .then(products => setState({ status: products.length ? 'ready' : 'empty', products, error: null }))
      .catch(error => {
        if (error.name !== 'AbortError') setState({ status: 'error', products: [], error });
      });
    return () => controller.abort();
  }, []);

  if (state.status === 'loading') return <p role='status'>Loading products…</p>;
  if (state.status === 'error') return <p role='alert'>We could not load the catalog. Try again.</p>;
  if (state.status === 'empty') return <p>No products are available yet.</p>;
  return <ProductGrid products={state.products} onAdd={product => dispatch({ type: 'add', product })} />;
}

In production, validate response fields, cancel obsolete requests, and decide how stale data should be cached. Do not trust a client-supplied price when creating an order.

Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Which checkout approach should a React store use?

Use hosted checkout when minimizing payment code is the priority. Use Checkout Sessions with Elements when you need a custom checkout layout while Stripe still manages checkout state and payment details. In both cases, create the session on your server and keep secret keys there.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Customer experience Implementation scope Use when
Stripe hosted Checkout Redirects to a payment page hosted by Stripe Smallest payment surface; your server creates a session and the browser redirects You want a fast, lower-maintenance launch
Checkout Sessions with Elements Checkout remains in your page with Stripe Elements providing payment UI More layout work while Stripe handles checkout state and payment collection Brand continuity and a custom page justify the extra integration

Hosted Checkout flow

  1. The browser sends the cart’s product IDs and quantities to your server.
  2. The server loads authoritative prices and availability, creates a Checkout Session, and returns only the session URL or client-safe identifier.
  3. The browser redirects to that URL.
  4. Your success and cancellation pages display the appropriate result, while a server webhook records the final order after payment confirmation.

Never place a secret key in React source, a public environment variable, or a browser request. Validate quantities and product IDs server-side, and make webhook handling idempotent so a retry cannot create duplicate fulfillment.

Should I use a commerce API or build the backend myself?

A commerce API reduces the amount of catalog, variant, cart, and checkout infrastructure you have to implement. Shopify’s Storefront API, for example, provides product and variant data, cart creation, and checkout URL generation. A direct database or JSON file is acceptable for a demo, but inventory, pricing, authentication, order management, and validation become your responsibility.

Backend choice Capabilities you receive Work that remains
Static or direct product data Simple catalog rendering and local cart behavior Inventory accuracy, secure pricing, customer accounts, orders, refunds, and fulfillment
Commerce API Catalog entities, variants, cart primitives, and a checkout handoff API integration, access control, storefront presentation, webhooks, and any custom business rules
Custom commerce backend Full control over data model and workflows Every commerce feature, security control, operational process, and maintenance task

Keep API credentials with the server or a narrowly scoped public token intended for browser use. Map API errors to friendly UI messages without exposing internal response details.

How do I make the store accessible and responsive?

Accessibility is part of the component contract, not a final polish step. Give every route a meaningful document title; MDN notes that accurate page titles are important for accessibility. Use real buttons for cart actions, labels for quantity controls, visible focus styles, and alt text that conveys the purpose of each product image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
  • Ensure keyboard users can open product links, change quantities, remove items, and reach checkout without a mouse.
  • Use aria-live or a status region for cart-update feedback and loading messages.
  • Do not rely on color alone for sale status, errors, or stock state.
  • Use responsive CSS with a single-column layout on narrow screens and a grid that can collapse without horizontal scrolling.
  • Keep touch targets large enough to activate comfortably and preserve focus after a quantity update.

Test with keyboard navigation, a screen reader, zoom, reduced-motion preferences, and a narrow viewport. Check that an empty cart has a clear path back to the catalog.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What should I test before deploying?

Test the complete purchase path with a payment provider’s test mode and a non-production catalog. Verify both successful and cancelled payments, network failures, duplicate clicks, invalid quantities, expired sessions, and webhook retries.

  • Catalog: products render, broken images have useful alt text, and an empty response is understandable.
  • Cart: adding the same variant merges quantities, quantity zero removes the line, subtotal formatting uses the selected currency, and the empty state is reachable.
  • Routing: direct loads of product, cart, and completion URLs work after deployment; unknown product IDs show a not-found page.
  • Security: secret keys stay server-side, prices are reloaded from the backend, and user-controlled text is escaped.
  • Payments: the server validates the cart, the success page does not itself mark an order paid, and webhook processing is idempotent.

How do I build and deploy the finished store?

For a Vite client-only app, run npm run build and publish the generated static output through a host configured for your router’s fallback. The browser still needs a reachable API and a server endpoint for checkout if you use hosted payments. A React framework can add server rendering or server features when SEO, personalization, or backend work becomes important, but deploy it on a runtime that supports the framework’s chosen rendering mode.

Set production environment variables on the server, configure allowed origins and webhook endpoints, enable HTTPS, and keep test and live payment credentials separate. Monitor failed API requests and payment webhooks after launch; a storefront that renders correctly can still fail operationally if orders are not recorded or fulfilled.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I keep cart contents after a browser refresh?

Yes. Serialize a versioned cart shape to localStorage and hydrate it when the provider starts, but treat the stored values as display state only. On checkout, reload current prices, variants, stock, and currency from the server because local storage can be stale or modified.

Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Do I need user accounts for a first React store?

No. Guest checkout is usually the smallest path for an initial release. Add accounts when customers need order history, saved addresses, subscriptions, or personalized pricing, and keep authentication on the server rather than inventing a browser-only identity system.

How should shipping and tax be calculated?

Collect the destination and any required address details before finalizing the payment session, then calculate shipping and tax in the commerce or payment backend that has the authoritative rules. Do not derive legally significant totals solely from JavaScript running in the browser.

What happens if a customer closes the tab during payment?

The payment provider’s webhook, not the React success page, should be the source of truth for payment completion. Store a pending order or checkout reference before redirecting, then reconcile it when the webhook arrives and provide a way for support to inspect unmatched sessions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When should I move from Vite to a framework?

Move when server rendering, metadata and SEO requirements, authenticated server data, route-level loading, or a larger team justify integrated conventions. You can keep the same components and cart domain logic while replacing the application shell and data-loading layer.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.