
✅ React Web App Development Guidelines
This document provides a comprehensive and detailed set of guidelines tailored specifically for developing robust React web applications within Visual Studio Code using Augment. The goal is to ensure your project is built with scalability, modularity, maintainability, security, and future extensibility at its core.
Copy and Paste this document, after this point, into Augment after your design description.Augment will accept your application description and the following guidelines as the basis for the design of your new React Web Appplication.
✅ React Web App Development Guidelines
🔒 Storage & Data Handling
- IndexedDB as Primary Storage: Use modern IndexedDB wrappers like idb or Dexie for efficient, asynchronous, transactional data persistence that outperforms localStorage for complex data. Consider building custom wrappers around these libraries for additional tailored functionality.
-
Promise-based Abstractions: All data access should be wrapped in Promise-based APIs or async/await to ensure clean, non-blocking code.
This pattern facilitates error handling and seamless integration with React hooks. -
Versioned Schema Management & Data Migrations: Implement explicit versioning for your IndexedDB schema.
When schema updates are required, write robust migration functions that carefully transform or archive legacy data without loss.
Automate this process to avoid runtime issues during app upgrades. -
React Hooks for Encapsulation: Create custom hooks like
usePersistentStore()
that encapsulate data handling logic,
abstracting complexities of IndexedDB and exposing clean APIs for components.
These hooks should also support subscription to changes, optimistic UI updates, and error states. -
Factory Reset with User Safeguards: Implement a deliberate 2-step reset procedure:
- User triggers reset from the UI, e.g., a “Reset App Data” button.
- A modal confirmation dialog appears with a clear warning and an optional “Undo” delay before actual clearing.
This prevents accidental data loss and improves user trust.
-
Graceful QuotaExceededError Handling: Detect storage quota limitations early, catch
QuotaExceededError
, notify users with friendly UI messages,
and optionally provide data pruning or compression options.
Implement fallback strategies or sync data with server storage if applicable. -
Encrypt Sensitive Data Client-Side: Use libraries like
crypto-js
or
the nativewindow.crypto.subtle
API for cryptographic operations.
Encrypt Personally Identifiable Information (PII), session tokens, or other sensitive values before storage.
Avoid plaintext persistence anywhere. -
Security of Credentials: Avoid storing passwords, access tokens, refresh tokens, or credentials in localStorage or IndexedDB unless encrypted.
Prefer ephemeral in-memory storage for critical secrets, renewing tokens frequently and using secure HTTP-only cookies for authentication where possible.
🧱 Architecture & Design Patterns
-
Adapted MVC Model for React: Use a clear separation of concerns to maintain clean architecture:
- Model: Encapsulate all business logic, API service clients, persistent data stores, and data normalization.
- View: Develop fully stateless, pure functional React components focused on UI rendering only.
- Controller: Build custom React hooks and Context Providers to manage state, side effects, and orchestration between Model and View.
-
Model Context Protocol (MCP) as Universal Language: Implement MCP as the foundational protocol for ALL communication - internal, external, and inter-application.
MCP serves as the universal language that enables AI agents to seamlessly interact with and control your React application, making it part of a larger AI-driven ecosystem. -
Normalize API Data: Use tools like
normalizr
or hand-crafted reducer mapping functions to flatten and normalize complex API payloads,
facilitating predictable state updates and efficient cache invalidation. -
Feature Flags & Policy-Based Access Control: Integrate feature toggles and role-based access control (RBAC) at the UI and API layers,
using Higher-Order Components (HOCs) or hooks to dynamically control visibility, access, and functionality per user or environment. -
Secure-by-Design Principles: Enforce Content Security Policy (CSP), Subresource Integrity (SRI), and secure HTTPS origins throughout.
Incorporate strict HTTP headers, and ensure minimal attack surfaces by sanitizing all inputs.
🧠 Model Context Protocol (MCP) - AI-First Architecture
MCP is the universal protocol that enables AI agents to interact with your React application.
Design your app as MCP-native from the ground up, assuming AI will be the primary interface for performing work.
Every component, service, and data flow should be accessible and controllable via MCP endpoints.
🤖 AI-First Design Principles
- AI as Primary User: Design APIs, state management, and business logic assuming AI agents will be the main consumers, not just human users.
- MCP-Native Components: Every React component should expose its capabilities through MCP tools and resources.
- Declarative Intent: Structure your app so AI can express high-level intentions that get translated into specific UI actions.
- Universal Protocol: MCP serves as the common language between different AI-enabled applications in your ecosystem.
🏗️ Core MCP Modules
- SessionManager: Exposes authentication, token lifecycle, and session state via MCP tools for AI-driven user management.
- MemoryCache: Provides MCP access to local settings, drafts, preferences - allowing AI to persist and retrieve context across sessions.
- ToolRegistry: Dynamically loads/unloads features based on AI requests, user roles, or runtime conditions via MCP resource discovery.
- StateSyncEngine: Handles real-time state updates and conflict resolution, exposing state manipulation tools for AI coordination.
Mermaid Diagram: AI-First MCP Architecture
AI[AI Agent] -->|MCP Protocol| MCPServer[MCP Server]
MCPServer -->|Tools & Resources| SessionManager
MCPServer -->|Tools & Resources| MemoryCache
MCPServer -->|Tools & Resources| ToolRegistry
MCPServer -->|Tools & Resources| StateSyncEngine
UI[React UI] -->|Hooks| SessionManager
UI -->|Context Providers| MemoryCache
UI -->|Role-based Hooks| ToolRegistry
UI -->|Side Effects| StateSyncEngine
SessionManager -->|API calls| Backend["/api/session"]
MemoryCache -->|API calls| Backend2["/api/memory"]
ToolRegistry -->|API calls| Backend3["/api/tools"]
StateSyncEngine -->|API calls| Backend4["/api/state"]
MCPServer -.->|Observes| UI
AI -.->|Controls| UI
� MCP-Native React Implementation Patterns
Build React components and hooks that are inherently AI-accessible through MCP from day one.
🎯 MCP-Aware Components
-
Expose Component Capabilities: Every component should register its available actions as MCP tools:
// UserProfileComponent.tsx const UserProfile = () => { useMCPTool('user.profile.update', updateProfile); useMCPTool('user.profile.export', exportProfile); useMCPResource('user.profile.data', profileData); return <div>...</div>; };
-
Declarative State Exposure: Make component state accessible to AI via MCP resources:
// FormComponent.tsx const ContactForm = () => { const [formState, setFormState] = useState({}); useMCPResource('form.contact.state', formState); useMCPTool('form.contact.submit', handleSubmit); useMCPTool('form.contact.validate', validateForm); return <form>...</form>; };
-
AI-Driven Navigation: Expose routing and navigation as MCP tools:
// Navigation.tsx const Navigation = () => { useMCPTool('nav.goto', (path) => navigate(path)); useMCPTool('nav.back', () => navigate(-1)); useMCPResource('nav.current', location.pathname); return <nav>...</nav>; };
🔄 MCP State Management
- Global State as MCP Resources: Expose all global state through MCP for AI visibility and control.
- Action Dispatching via MCP Tools: Allow AI to trigger state changes through well-defined MCP tool interfaces.
- Real-time State Sync: Use MCP's streaming capabilities to keep AI agents synchronized with application state changes.
🛠️ Custom MCP Hooks
- useMCPTool: Register component actions as callable MCP tools.
- useMCPResource: Expose component data as readable MCP resources.
- useMCPPrompt: Create dynamic prompts that AI can use to understand component context.
- useMCPSubscription: Subscribe to AI-initiated events and state changes.
🌐 MCP Ecosystem & Inter-Application Communication
When every application is MCP-native, AI agents can orchestrate complex workflows across multiple applications seamlessly.
🔗 Cross-Application Workflows
- Universal Protocol: MCP enables AI to treat different applications as interchangeable tools in a larger workflow.
- Composable Applications: Design your React app to be a composable piece in larger AI-orchestrated business processes.
- Shared Context: Use MCP's context sharing capabilities to maintain state and context across different applications.
- Workflow Orchestration: AI can coordinate complex multi-step processes that span multiple MCP-enabled applications.
🤝 Application Interoperability
- Standard Interfaces: Implement common MCP tool patterns (CRUD operations, navigation, data export/import) for consistency across applications.
- Resource Discovery: Expose application capabilities through MCP resource discovery so AI can understand what your app can do.
- Event Broadcasting: Use MCP to broadcast significant events that other applications in the ecosystem might need to react to.
- Data Portability: Design data structures and APIs that facilitate easy data movement between MCP-enabled applications.
�💡 Code Safety & Best Practices
-
Enable
'use strict'
mode globally for improved error detection and stricter parsing rules.
This helps catch silent errors early in the development lifecycle. -
Use clear, descriptive, and self-documenting naming conventions, e.g.,
useUserSession
for hooks managing user authentication state, orFormStateProvider
for context providers managing complex form state. -
Validate and sanitize all user inputs rigorously using
libraries likeyup
,zod
, or integrations withreact-hook-form
.
Enforce schema-driven validation to prevent invalid or malicious data. -
Prevent global scope pollution:
Organize code in ES modules, avoid global variables, and use state managers such as
Zustand or
Redux Toolkit
for predictable global state. -
Implement robust error handling:
Use ReactErrorBoundary
components for UI crash recovery,
fetch abort controllers to cancel unnecessary API calls,
and automatic retry logic with exponential backoff on transient network failures. -
Structured Error Logging: Log errors in a consistent format:
[HH:MM:SS AM/PM] <Element> tag #X: <message> at line L, column C
This enables easier debugging and error tracking across the application. -
Fallback Behavior: Provide robust error handling with fallback behavior for all critical operations.
Ensure the application remains functional even when non-critical features fail. -
Network Request Resilience: Add timeouts and retry logic to all fetch requests.
Implement exponential backoff for failed requests and graceful degradation for offline scenarios. -
Avoid Global State Pollution: Use IIFEs (Immediately Invoked Function Expressions) or ES modules to prevent global scope pollution.
Organize code in modules and avoid global variables that can cause naming conflicts.
📄 Documentation & Versioning
-
Document every custom hook, utility function, context provider, and API interaction with
TSDoc orJSDoc
to enable clear IDE tooltips and automated docs generation. -
Comprehensive Documentation: Document all functions, data structures (objects, arrays), and public APIs in both README and inline comments.
Maintain comprehensiveREADME.md
with setup, architectural decisions, and coding standards. -
Version Management: Update app and README version numbers on each release or change.
Use semantic versioning (semver) format (MAJOR.MINOR.PATCH).
Maintain a detailedCHANGELOG.md
with summaries, version bumps, and test logs. -
Manage environment variables securely:
Use.env.local
for secret keys and API endpoints specific to developer machines,
and provide a sanitized.env.example
template for collaborators. -
Generate and maintain a
/docs/
folder automatically using tools like:- Swagger/OpenAPI for REST API contracts and endpoint documentation
- Mermaid for architectural diagrams
- Madge for dependency graphs
-
Automated Documentation: Use tools like
documentation.js
to automatically generate documentation from your JSDoc/TSDoc comments. These tools work together - write good JSDoc comments in your code, then use documentation.js to generate readable documentation from them. - Update .gitignore with any new changes that are relevant.
🧑🦽 UI/UX & Accessibility
-
Always use semantic HTML5 elements (
<main>
,<nav>
,<section>
, etc.) and ARIA roles
to improve screen reader compatibility and SEO. -
Provide a fully responsive design that adapts to screen size, using CSS variables for themes,
media queries for breakpoints, and prefers-color-scheme for dark mode. -
Use skeleton loaders or shimmer placeholders during data fetching to improve perceived performance.
Include a<noscript>
fallback message for users with JavaScript disabled. -
Support comprehensive keyboard navigation, logical tab order, and focus states.
Regularly audit accessibility using tools like Lighthouse, axe-core, and manual testing with screen readers. -
HTML/CSS Integrity: Keep all HTML/CSS intact; changes must be drop-in compatible.
Implement ARIA attributes, keyboard navigation, high color contrast, and screen reader testing. -
Dark Mode Support: Add dark mode toggle or media query support with preference storage.
Use CSS custom properties for theme switching and respect user's system preferences. -
Loading States: Use Skeleton Screens (not spinners) for async loading.
Handle dynamic rendering for delayed/partial data to improve perceived performance. -
SEO & Discoverability: Include basic SEO (title, description, OpenGraph) and a
robots.txt
.
Ensure proper meta tags and structured data for search engine optimization. -
Fixed Readme Button: Add a fixed top "Readme" button that:
- Opens scrollable popup (Markdown via Marked.js) of readme.md markdown
- Has visible "X" close button
- Styled clearly and overlays content
🚀 Performance & Optimization
-
Lazy-load components, routes, and heavy dependencies with
React.lazy
and
Suspense
to reduce initial bundle size and speed up load times. -
Leverage service workers via
Workbox
to enable Progressive Web App (PWA) features like offline support, caching, and background sync. -
Defer loading of non-critical CSS and JavaScript.
Use passive event listeners and throttle/debounce event handlers to reduce main thread congestion. -
Continuously monitor runtime performance using
web-vitals,
Lighthouse audits, and Chrome DevTools profiling.
Use results to identify bottlenecks and guide optimizations. -
PWA Features: Include a complete
manifest.json
for PWA features.
Use Service Workers for caching, offline support, and update handling. -
Offline-First Strategy: Use offline-first caching with write-through sync on reconnect.
Simulate slow networks/devices in testing to ensure robust performance. -
Immutable Updates: Prefer immutable updates using libraries like Immer.js or Redux.
This improves performance and makes state changes more predictable. -
Event Optimization: Throttle events (scroll/resize) via
requestAnimationFrame
or debounce.
Use passive event listeners to improve scroll performance. -
Asset Optimization: Use content hashing for long-term asset caching.
Prefetch assets based on user behavior or route visibility. -
Code Splitting: Eliminate unused code with tree shaking; import libraries modularly.
Use dynamic imports for route-based and component-based code splitting.
🧪 Testing & Build Pipeline
-
Write unit and integration tests using
jest
and @testing-library/react.
Use Cypress or Playwright for end-to-end testing with realistic user workflows. -
Automate testing and deployment.
Configure pipelines to run linting, tests, builds, and deploy only on passing workflows. -
Track and enforce code coverage thresholds to maintain high test quality.
Set up pre-merge lint/build/test gates on all pull requests to enforce code quality and consistency. -
Comprehensive Test Coverage: Write unit tests covering:
- Positive/negative test cases
- Edge/boundary conditions
- State transitions
- Simulated failures
- Performance benchmarks
-
Visual Regression Testing: Add automated UI regression tests with visual snapshots.
Use tools like Percy, Chromatic, or jest-image-snapshot for visual testing. -
Build Automation: Include build scripts (npm, Makefile) for lint, test, and deploy steps.
Automate the entire development workflow from code commit to deployment.
♻️ Reusable Design Patterns & Architectural Practices
-
Dependency Injection (DI): Inject services via containers or factories for testing flexibility.
Use React Context Providers to inject APIs, services, or config throughout the app. -
Command Pattern: Encapsulate user actions (e.g., SubmitFormCommand) for undo/logging capabilities.
This enables action replay, undo functionality, and comprehensive audit trails. -
Observer Pattern: Use pub/sub or RxJS for reactive UI state management.
Apply using React'suseEffect
hook to reactively respond to state or prop changes. -
State Machine Pattern: Use XState or FSMs for onboarding and multi-step flows.
Manage complex states to model UI workflows and business logic explicitly and reliably. -
Strategy Pattern: Swap logic at runtime (e.g., pricing algorithms, rendering strategies).
Enables flexible behavior modification without code changes. -
Adapter Pattern: Normalize third-party/legacy APIs with consistent interfaces.
Create adapters to bridge incompatible interfaces and data formats. -
Repository Pattern: Encapsulate DB/API logic behind a clean interface.
Abstract data access and provide consistent CRUD operations. -
Facade Pattern: Hide subsystem complexity with clean public APIs.
Provide simplified interfaces to complex subsystems. -
Scoped Singleton Pattern: Share config or auth state via closures/modules.
Ensure single instances of critical services while maintaining scope isolation. -
Template Method Pattern: Provide overridable hooks (e.g., beforeSave, afterLoad).
Define algorithm structure while allowing customization of specific steps. -
Memento Pattern: Save and restore session or undo state.
Enable state snapshots for undo/redo functionality and session recovery. -
Module Federation: Use Webpack for scalable microfrontend modules.
Enable independent deployment and development of application modules.
🔐 Security Best Practices
-
Content Security Policy (CSP): Apply CSP nonces to dynamically injected scripts.
Implement CSP with nonces for inline scripts and strict sources for scripts, styles, and media.
This protects against XSS and injection attacks. -
Zero Trust Security Model: Follow Zero Trust principles:
Always validate and verify tokens and permissions server-side,
never trust client-side assertions alone. -
Least Privilege Principle: Enforce Least Privilege at both UI and API layers.
Ensure users and components only receive access strictly necessary for their roles.
🧠 Semantic Type Prompts for AI-Assisted Extensions
Define detailed semantic annotations within your source code to enable intelligent AI-powered code generation, refactoring, and module extension via Augment or similar tools.
-
Include semantic block comments at the top of each module describing its purpose, type, extensibility, and AI use cases, for example:
/** * SemanticType: PersistentLocalStorageHook * Description: Provides reactive access to IndexedDB for caching user preferences and session data. * ExtensibleByAI: true * AIUseCases: * - Add encryption layer * - Support export/import feature * - Migrate schema version to add "lastLogin" timestamp */
-
Maintain a centralized
augment.schema.json
metadata file describing all modules, semantic types, and extensibility flags:{ "modules": { "UserForm.tsx": { "SemanticType": "DynamicFormComponent", "Description": "Form for editing user profile with validation.", "ExtensibleByAI": true, "AIUseCases": ["Add fields", "Inject custom components", "Reorganize layout"] } } }
-
Common semantic types to use include:
- DynamicFormComponent
- AuthSessionService
- RoleBasedToolLoader
- MemoryCacheEngine
- APIInteractionModule
-
Flag modules explicitly as
ExtensibleByAI: true
only when safe to enable controlled AI augmentation.
- Lock Hackers Out for Good!
- Don’t Let Tech Failures Destroy You
- Why AI-First Apps Will Rule the Future
- ✅ React Web App Development Guidelines
- Authenticator Shock: Your Data's Gone
- Outmaneuver Rivals with OODA Power
- Office Makeover: Dual Upgrade Day
- Upgrade Chaos? Kyle Rescued It!
- The Web Connector from Hell: A Lesson in Practical IT Strategy
- 10 Ways Google NotebookLM Will Blow Your Mind 🤯
- Business Search – Turbo-Charge Your B2B Growth
- How to Set Up Windows 11 Without a Microsoft Account
- The Google Ads Playbook: How to Advertise Your Business On Google
- Transform Docs with NotebookLM
- 🚨 New Meta Quest Scam Targeting Facebook Users
- Why Passwords Matter
- Quick Fix: Helping a Customer Save Her Printer
- Funnel Profit Secrets Exposed!
- How Readable Content Establishes Authority and Boosts Your SEO Ranking
- SMB Cybersecurity: Tips & Hacks
- UNLOCKING FIRST PRINCIPLES EXPOSED!
- Blogging Ignites Business Growth Today
- GPU Showdown: Mind-Blowing Secrets
- Unlock Mega Speeds: More RAM, More Power!
- Unveiling the Mystery Behind Your PC’s BIOS: What You Need to Know!
- CISA Windows GPO Settings Checklist
- Master Windows Security with GPOs
- Step-by-Step PowerShell GPO Example
- Unlocking the Secrets of Computer Registries
- Master Google Analytics Today
- Ancient Server Fails: Tech Fixes on a Budget!
- 10 NIST Secrets to Lock Down Windows PC
- Unlock Excel’s Hidden AI Powers
- Fast Same-Day On-Site IT Solutions for SMBs | My Tech on Wheels
- Don’t Let Disaster Ruin You
- Email Slow as Snail Mail? Fix It Now!
- Stop Receiving Spam Emails From Nigerian Princes
- Kaspersky’s Secret Swap: Is Your Antivirus Software Safe?
- Bitcoin’s Future $20 Million Predictions by 2040! – 08-28-2024
- 5 Essential IT Skills for Lucrative DevOps Jobs
- Understanding Agile Development
- CI/CD Tutorial for Beginners
- Boost Your CI/CD Pipeline with ESLint
- Setting Up a Heroku Deployment with Jenkins
- Setting up a Docker Pipeline in Jenkins
- Integrate GitHub with Jenkins
- Uncovering Microsoft Tracking: 5 Alarming Data Capture Practices in Windows 10 and 11
- What kind of IT service does your business deserve?
- myTech.Today Top 5 Benefits of Managed IT Services for SMBs
- First Principles Thinking for Problem Solving: 3 Real-World Examples
- Master Computer Listings: Decode and Choose Wisely
- Stop iPhone Hotspot Issues on Windows PCs: 5 Tips
- Boost Your Career with These 5 Essential IT Skills for High-Paying DevOps Positions
- 10 Steps to Thriving as a Digital User Experience Tester
- Mastering Test Case and Test Scenario Development with Zephyr and Selenium-Java
- Master Troubleshooting Tools: GraphQL – Developer Tools – Charles Proxy and Postman
- Top 6 Online Resources for Hiring Skilled Employees Fast
- End of Petro-Dollar Agreement – June 9th 2024: Impact & Investment Strategies
- Top 5 Global Challenges for Businesses in 2024 and How to Overcome Them!
- The Benefits of Using Open Source Developer Journal Software Compared to Paid Versions
- Understanding Data Analysis: A Comprehensive Guide
- The Benefits of Using Open Source Developer Journal Software Compared to Paid Versions
- Understanding MVC in Software Development
- Reflections on My Work at Columbia Home Products
- Top 5 Cybersecurity Strategies Every SMB Should Implement
- Automation Software: Transforming Industries Beyond DevOps
- Optimizing Data Management with Relational Database Design
- Mastering Object-Oriented Design for Robust Software Solutions
- Important Information Regarding Google Workspace Folder Management
- Streamlining Software Development with CI/CD Pipelines
- Harnessing Microservices Architecture for Scalable Business Solutions
- Predictive Modeling: Driving Future Business Success for SMBs
- Harnessing the Power of Statistical Modeling for SMBs
- Leveraging Data Science Methodologies for SMB Success
- Choosing the Right Software Architecture Style for Your Business
- Driving Innovation with Design Thinking for SMBs
- 🌐 5 Ways to Enhance Your Global Business Strategy for 2024!
- Incorporating Security by Design in AI Product Development
- Implementing Core Software Architectural Principles in Your Projects
- Mastering Data Modeling: Essential Principles for SMBs
- 🌐 7 Must-Know Global Trends in E-commerce for 2024!
- Select 🌐 6 Steps to a Smarter Office: Enhance Productivity with Smart Office Technology!
- Using Big Data to Drive Small Business Growth
- Improving Customer Experience Through Technology
- Select The Future of AI in Small Business Operations
- Strategic IT Decisions: Planning for Long-Term Success
- Mobile Solutions for Business Efficiency
- Improving Customer Experience Through Technology
- 5 Revolutionary Ways IoT is Changing Small Businesses 🚀
- Transform Your Customer Service with These 6 Next-Level Chatbot Features!
- ⭐ Optimize Your Retail Strategy: 5 Tips for Maximizing In-Store Sales!
- Quantitative Data Analysis: A Brief Guide
- Top 20 Data Structures in Modern Programming
- myTech.Today Tools 2024
- Revolutionizing Web Design with ChatGPT and Modern Tools
- Understanding Database Normalization
- The Hidden Dangers of Phishing Scams: A Cautionary Tale
- Integrating Git with Visual Studio Code: A Comprehensive Guide
- Mastering Git and GitHub for Windows Users
- Unlocking the Power of Vagrant in Software Development
- Mastering Docker in Development: A Guide for Modern Developers
- Unlocking the Power of Swarms: A Comprehensive Guide
- Navigating the Maze: Escaping the Desktop Freeze Scam
- June 2023: More Apps & caution RE: .zip files
- June 2023: Exploring the New Frontier of AI Apps!
- Elevate Your IT Strategy with AI: Summer '23 Insights
- Discover 100 Top AI Tools: Weekly Tech Innovation Guide!
- 7 New Apps to Explore: Weekly Gems 💎
- Unlock 45+ AI Tools & Apps to Skyrocket Your Business Today!
- Unlock the Power of Speech-to-Text and AI Chatbots: Boost Your Productivity by 200%!
- 💥 Revealed: The Ultimate Collection of Hidden Software Gems for Business Owners! 💥
- ✨ Unlock Secret Software Gems: Boost Your Business Efficiency TODAY with Our Exclusive Weekly Newsletter! ✨