Full-Stack Web & React TypeScript Standard
Objective
Enforce strict TypeScript safety, runtime API contract validation, clean separation between UI components and data fetching, disciplined state hierarchy, and complete 4-state UI resilience aligned with ARCHITECTURE.md, CONVENTIONS.md, and SECURITY.md.
1. Strict TypeScript & Runtime Contract Validation
- Zero
anyPolicy: Never useany,@ts-ignore, or unguarded type assertions (res.json() as MyType) on external network payloads. Narrow unknown inputs with Zod schemas or explicit type guards. - Boundary Contract Enforcement: Every API client function must validate incoming responses against a Zod schema matching the backend Pydantic/OpenAPI contract and unwrap the standard response envelope (
CONVENTIONS.md):- Check
envelope.success === truebefore accessingenvelope.data. - Map
envelope.error(code,message,details) into a typedApiClientErrorinstance for UI error handling.
- Check
- Single Source of Truth for Types: Infer TypeScript types directly from Zod schemas (
z.infer<typeof UserSchema>) rather than maintaining duplicate manual interfaces that drift from runtime validation.
2. Component Architecture & Layering
Enforce the presentation boundary rules from ARCHITECTURE.md:
- API Clients (
services/api/orlib/api/):- Centralize
fetchwrappers, base URL resolution, auth header injection, request timeouts (AbortSignal.timeout), and Zod response parsing in dedicated client modules. - Components must never call raw
fetch(),axios, or database SDKs directly inside JSX files.
- Centralize
- Domain Hooks (
hooks/):- Encapsulate server cache queries, mutations, and multi-step form workflows inside custom hooks (
useDocumentAnalysis,useUpdateProfile).
- Encapsulate server cache queries, mutations, and multi-step form workflows inside custom hooks (
- Presentational & Container Components (
components/,pages/):- Keep components focused and under 250–300 lines. Extract reusable sub-components when a file mixes layout orchestration with complex interactive widgets.
- Define explicit
interface ComponentNamePropscontracts; avoidReact.FCimplicit children patterns.
3. State Management Hierarchy
Place state at the lowest, most specialized tier that satisfies the requirement. Never duplicate server state into global client stores:
- URL State (Search Params / Route Params): Filters, pagination, active tabs, search queries, and shareable view modes belong in the URL.
- Server Cache State (TanStack Query / SWR): All remote API data, loading flags, caching, background refetching, and cache invalidation belong in a dedicated server-state library.
- Local Component State (
useState/useReducer): Ephemeral UI interactions (modal open/close, hover state, controlled input drafts) stay local to the component. - Global Client State (Zustand / React Context): Reserved strictly for cross-tree client-only concerns (theme, sidebar collapse, active toast queue, session metadata).
4. React Hooks & Rendering Discipline
- No
useEffectfor Derived State: Never compute values from props or existing state insideuseEffect+setState. Compute derived values directly during render (or wrap expensive computations inuseMemoonly when profiled). - No Raw
fetchinuseEffect: Never write manualuseEffect(() => { fetch(...) }, [])data-fetching loops that lack deduplication, caching, retry logic, and race-condition cancellation. - Event-Driven Side Effects: Trigger mutations and analytics events inside user event handlers (
onClick,onSubmit), not via reactiveuseEffectwatchers. - Stable List Keys: Never use array indices (
index) as Reactkeyprops on dynamic, sortable, or filterable lists; use stable entity IDs.
5. Mandatory 4-State UI Matrix & Mutation Resilience
Every data-driven view or widget must explicitly handle all four asynchronous states—never ship happy-path-only rendering:
- Loading State: Render layout-preserving skeleton placeholders or accessible loading indicators (
aria-busy="true"). - Empty State: Render an intentional zero-data message explaining why nothing is shown and providing a clear next action (e.g., "Create first item" or "Clear filters").
- Error State: Render a user-safe error banner/card displaying a clear message and an explicit Retry action button (
refetch()), wrapped by a route-level Error Boundary. - Success State: Render the validated domain data cleanly.
- Form & Mutation Guardrails:
- Validate form inputs on the client with the same Zod schema used by the API boundary before submitting.
- Disable submit buttons while
isPendingis true to prevent duplicate requests, and invalidate affected server cache queries immediately on mutation success.
6. Accessibility & Frontend Security Baseline
- Semantic HTML & Keyboard Access: Use native
<button>,<a href>,<label htmlFor>, and<form>elements rather than clickable<div>tags. Providearia-labelon all icon-only interactive controls. - XSS Prevention: Never use
dangerouslySetInnerHTMLunless sanitized through a strict allowlist sanitizer (e.g., DOMPurify). - Client Bundle Secret Hygiene: Never reference server-only secrets in
VITE_*orNEXT_PUBLIC_*environment variables, as all public env vars are bundled into client JavaScript.
Anti-Patterns: Rejected vs. Accepted Implementation
Rejected (Raw Fetch in useEffect + any + Derived State Effect + Missing States)
export function ProjectList() {
const [projects, setProjects] = useState<any[]>([]);
const [count, setCount] = useState(0);
useEffect(() => {
fetch("/api/projects").then((r) => r.json()).then(setProjects); // Unvalidated any, no error/loading state
}, []);
useEffect(() => {
setCount(projects.length); // Unnecessary derived state effect
}, [projects]);
return <ul>{projects.map((p, i) => <li key={i}>{p.name}</li>)}</ul>;
}
Accepted (Zod Contract + Server Cache Hook + Derived Render + 4-State UI)
const ProjectSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
});
type Project = z.infer<typeof ProjectSchema>;
export function ProjectList() {
const { data: projects, isLoading, isError, refetch } = useProjectsQuery();
if (isLoading) return <ProjectListSkeleton />;
if (isError) return <ErrorState message="Failed to load projects." onRetry={refetch} />;
if (!projects || projects.length === 0) return <EmptyState title="No projects yet" />;
const projectCount = projects.length; // Computed directly during render
return (
<section aria-label={`Projects (${projectCount})`}>
<ul>
{projects.map((project: Project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
</section>
);
}