React E-commerce Practice: Interactive Code Generation and Engineering Decoupling Guide
AI coding tools generate React code faster than developers can write it, but the results often need restructuring before production use. This article compares interactive and fully automatic generation modes using measurable metrics, then walks through a practical React e-commerce example covering layered directory structure, service layer isolation, form validation with debouncing and request cancellation, and a step-by-step acceptance checklist. By the end, you can apply the same generation and refinement workflow to your own projects.
1. Key Takeaways First
Interactive generation with AI coding tools gives you more control over the outcome than fully automatic mode. However, generated code rarely works as-is. Developers still need to add layered architecture, service layer isolation, and form validation before a project becomes maintainable in the long run.
This article uses a React e-commerce application as an example and provides a reusable directory template, service interface patterns, async validation code, and an acceptance checklist for incremental generation. After reading, you can follow the same steps to generate and refine code in your own projects.
2. Two Generation Modes and How to Measure Them
Fully automatic mode means giving the tool one abstract instruction and letting it handle requirement breakdown, coding, and debugging in one shot. When something goes wrong in this mode, it is hard to trace the cause—you only see the final result. This article calls this the “black box effect.”
Interactive generation mode breaks the task into steps, with the developer confirming each step before moving to the next. To compare the two modes objectively, track these three metrics:
- First-run success rate: the percentage of projects that install and start without errors on the first generation attempt.
- Fix iterations: the number of back-and-forth rounds between developer and tool from first generation to a working page.
- Dependency errors: the count of missing dependencies, version conflicts, and similar issues reported during installation or build.
Record results using a table like the one below—one row per project, updated after each stage:
| Project | Mode | First-run success (yes/no) | Fix iterations | Dependency errors |
|---|---|---|---|---|
| shop | Interactive | Yes | 2 | 0 |
Interactive mode suits complex projects where controllability matters, but manual confirmation at each step costs time. For small utilities of a few files, one-off scripts, or prototypes, fully automatic mode is usually faster. The examples and acceptance criteria in this article target the former.
3. Example Environment and Scope
The example uses the following stack:
- Node.js 20 LTS
- React 18 with TypeScript
- Vite as the build tool
- react-router-dom 6.x for routing
- pnpm as the package manager
Create the project with:
pnpm create vite shop --template react-tscd shoppnpm installpnpm add react-router-dom@6pnpm dev
The business scope covers two parts. The first is the shopping flow: product detail page, purchase page, and purchase success page. The second is user management: login, registration, user center, orders, coupons, and settings. Together they test how well the tool handles routing, state flow, form handling, and UI consistency.
4. UI Quality: Turning “Looks Bad” into Verifiable Items
AI coding tools can quickly apply a consistent theme from natural language prompts, but detail pages often end up rough. Instead of vaguely saying “the UI isn’t good enough,” verify each item on this checklist. Every item has a clear pass criterion:
- Theme colors are centrally defined. Pass criterion: all colors come from the theme variable file; searching for values starting with
#in the component directories returns 0 results. - List pages handle all three states. Pass criterion: list pages show an empty state, a loading indicator, and an error message for empty data, loading, and failed requests respectively—never a blank page.
- Image placeholders are consistent. Pass criterion: a unified placeholder shows when an image URL fails, and every
imgtag has non-empty alt text.
Structure the product detail page like this:
ProductDetailPage├── ProductGallery image carousel, receives an images array├── ProductInfo name, price, stock status├── SpecSelector spec selection└── BuyButton navigates to purchase page, disabled when stock is 0
Wrap image fallback logic into a component. When loading fails, it switches to a placeholder, and a state flag prevents repeated error callbacks if the placeholder itself fails:
// src/components/SafeImage.tsximport { useState } from 'react';const FALLBACK_SRC = '/images/placeholder.png';export function SafeImage({ src, alt }: { src: string; alt: string }) {const [failed, setFailed] = useState(false);return (<imgsrc={failed ? FALLBACK_SRC : src}alt={alt || 'Product image'}onError={() => setFailed(true)}/>);}
5. Layered Architecture: Directory Tree and Splitting Criteria
A common problem in generated projects is a flat directory with everything in one level. Use this structure instead:
src/├── components/ pure presentational components, props only, no requests├── containers/ page-level containers, compose components and call hooks├── services/ data fetching and mock data, exposing a unified interface│ ├── types.ts│ ├── productService.ts│ ├── api/│ │ └── productApi.ts│ └── mock/│ └── productMock.ts├── hooks/ state logic wrapping service calls└── utils/ business-agnostic pure functions
The splitting criteria are simple. If a file contains both JSX and fetch calls, split it. If a utils function depends on React or specific business fields, move it to the appropriate module.
The core principle of the service layer is to define interfaces first, then provide implementations. Put interfaces in types.ts:
// src/services/types.tsexport interface Product {id: string;name: string;price: number;images: string[];}export interface ProductService {getProduct(id: string): Promise<Product>;}export interface UserService {checkUsername(name: string, signal?: AbortSignal): Promise<boolean>;}
The real API and mock data each implement this interface, switched via environment variables. Here is the real implementation:
// src/services/api/productApi.tsimport type { ProductService } from '../types';export const apiProductService: ProductService = {async getProduct(id) {const res = await fetch(`/api/products/${encodeURIComponent(id)}`);if (!res.ok) throw new Error(`Failed to fetch product: ${res.status}`);return res.json();},};
The mock implementation simulates a small delay and keeps error behavior consistent with the real API:
// src/services/mock/productMock.tsimport type { Product, ProductService } from '../types';const products: Product[] = [{ id: '1', name: 'Sample product', price: 99, images: ['/images/demo-1.jpg'] },];export const mockProductService: ProductService = {async getProduct(id) {await new Promise((resolve) => setTimeout(resolve, 300));const found = products.find((p) => p.id === id);if (!found) throw new Error(`Product not found: ${id}`);return found;},};
Put the switching logic in a single entry point:
// src/services/productService.tsimport type { ProductService } from './types';import { apiProductService } from './api/productApi';import { mockProductService } from './mock/productMock';const useMock = import.meta.env.VITE_USE_MOCK === 'true';export const productService: ProductService = useMock? mockProductService: apiProductService;
When connecting a real backend, you only need to replace the implementation in the api directory—components and hooks stay untouched. Configure environment variables per environment:
# .env.developmentVITE_USE_MOCK=true# .env.productionVITE_USE_MOCK=falseVITE_IMAGE_BASE_URL=https://cdn.example.com
Note that in Vite, variables prefixed with VITE_ are bundled into frontend code, so only public configuration belongs there—image domains or mock toggles, for example. Secrets must stay on the server and never appear in any VITE_ variable.
6. Form Validation: Separate Sync and Async Checks
Synchronous validation covers required fields, length, and format. It runs as the user types and needs no server request. The following function returns an error message, or null when valid:
// src/utils/validators.tsexport function validateUsername(value: string): string | null {if (!value.trim()) return 'Username cannot be empty';if (value.length < 4 || value.length > 16) return 'Username must be 4 to 16 characters';if (!/^[a-zA-Z0-9_]+$/.test(value)) return 'Only letters, numbers, and underscores are allowed';return null;}
Asynchronous validation covers checks that require a server call, such as whether a username is already taken or whether a coupon code is valid. Two common problems arise. First, firing a request on every keystroke wastes resources and produces many pointless responses. Second, an earlier request may return after a later one, causing the UI to display a stale result. The solution is debouncing plus cancelling the previous request whenever the input changes.
First, add a signal parameter to the service interface so cancellation propagates to fetch:
// src/services/api/userApi.tsimport type { UserService } from '../types';export const apiUserService: UserService = {async checkUsername(name, signal) {const res = await fetch(`/api/users/check?name=${encodeURIComponent(name)}`,{ signal },);if (!res.ok) throw new Error(`Validation failed: ${res.status}`);const data: { taken: boolean } = await res.json();return data.taken;},};
Then wrap the debounce and cancellation logic in a hook. The component only reads the resulting status:
// src/hooks/useUsernameCheck.tsimport { useEffect, useState } from 'react';import { userService } from '../services/userService';export type CheckStatus = 'idle' | 'checking' | 'available' | 'taken' | 'error';export function useUsernameCheck(username: string, delay = 400): CheckStatus {const [status, setStatus] = useState<CheckStatus>('idle');useEffect(() => {if (!username) {setStatus('idle');return;}const controller = new AbortController();setStatus('checking');const timer = setTimeout(async () => {try {const taken = await userService.checkUsername(username, controller.signal);setStatus(taken ? 'taken' : 'available');} catch {// Cancelled requests should not update state, so the latest result is not overwrittenif (!controller.signal.aborted) setStatus('error');}}, delay);return () => {clearTimeout(timer);controller.abort();};}, [username, delay]);return status;}
In the form, the submit button’s availability depends on both the sync errors and the async status:
- If a sync error exists, the button is disabled and the error message appears below the input.
- When the async status is checking, the button is disabled and shows “Validating…”.
- When the async status is taken, the button is disabled with the message “Username is already taken”.
- When the async status is error, the button stays disabled with the message “Validation failed, please try again later”. This case must never be silently allowed through—otherwise the user submits unchecked data.
const syncError = validateUsername(username);const asyncStatus = useUsernameCheck(username);const canSubmit = !syncError && asyncStatus === 'available';
7. Acceptance Checklist for Incremental Generation
After each step, run through this checklist once. Only proceed to the next step once everything passes. Every item can be executed or observed directly.
Directory structure check:
- The five directories—components, containers, services, hooks, utils—exist under
src. - Searching for
fetch(in the components directory returns no results. - Searching for
from 'react'in the utils directory returns no results.
Service layer interface check:
- All data types and method signatures are defined in types.ts.
- Components and hooks never call fetch directly; they only call objects exported by the service layer.
- Starting the app with
VITE_USE_MOCKset to true and false both render pages correctly. - After replacing any implementation in the api directory, the app runs without modifying component code.
Form validation check:
- Entering invalid input shows the error message immediately as the user types.
- When typing rapidly, the Network panel shows only one request—not one per keystroke.
- When the input changes, the previous unfinished request is cancelled.
- When the async request fails, the page shows an error message and the submit button stays disabled.
- When a sync error exists or the async check fails, the submit button is disabled.
Startup and dependency check:
- Running
pnpm installcompletes without errors; the dependency error count is 0. - Running
pnpm devopens the homepage in the browser and navigation works. - Fill in the metrics table with the three metrics from this article; the first-run success rate and fix iterations are up to date.
8. Scope and Boundaries
The directory template, service interface patterns, and acceptance checklist in this article suit medium-to-large frontend projects with multiple pages, long-term maintenance needs, and a real backend to integrate. For utilities of a few files, one-off scripts, or demos-only prototypes, full layering adds unnecessary files. In those cases, fully automatic mode is the better fit—just keep the essential validation and error handling in place.
