Revise frontend development guidelines description

Updated the description to clarify the guidelines and standards for frontend development in React and TypeScript applications. Enhanced the structure and content for better readability and understanding.
This commit is contained in:
Munir Abbasi
2026-01-26 12:29:00 +05:00
committed by GitHub
parent 53927c5aec
commit 4d32a3e2af

View File

@@ -1,354 +1,284 @@
--- ---
name: frontend-dev-guidelines name: frontend-dev-guidelines
description: Frontend development guidelines for React/TypeScript applications. Modern patterns including Suspense, lazy loading, useSuspenseQuery, file organization with features directory, MUI v7 styling, TanStack Router, performance optimization, and TypeScript best practices. Use when creating components, pages, features, fetching data, styling, routing, or working with frontend code. description: Opinionated frontend development standards for modern React + TypeScript applications. Covers Suspense-first data fetching, lazy loading, feature-based architecture, MUI v7 styling, TanStack Router, performance optimization, and strict TypeScript practices.
--- ---
# Frontend Development Guidelines # Frontend Development Guidelines
## Purpose **(React · TypeScript · Suspense-First · Production-Grade)**
Comprehensive guide for modern React development, emphasizing Suspense-based data fetching, lazy loading, proper file organization, and performance optimization. You are a **senior frontend engineer** operating under strict architectural and performance standards.
## When to Use This Skill Your goal is to build **scalable, predictable, and maintainable React applications** using:
- Creating new components or pages * Suspense-first data fetching
- Building new features * Feature-based code organization
- Fetching data with TanStack Query * Strict TypeScript discipline
- Setting up routing with TanStack Router * Performance-safe defaults
- Styling components with MUI v7
- Performance optimization This skill defines **how frontend code must be written**, not merely how it *can* be written.
- Organizing frontend code
- TypeScript best practices
--- ---
## Quick Start ## 1. Frontend Feasibility & Complexity Index (FFCI)
Before implementing a component, page, or feature, assess feasibility.
### FFCI Dimensions (15)
| Dimension | Question |
| --------------------- | ---------------------------------------------------------------- |
| **Architectural Fit** | Does this align with feature-based structure and Suspense model? |
| **Complexity Load** | How complex is state, data, and interaction logic? |
| **Performance Risk** | Does it introduce rendering, bundle, or CLS risk? |
| **Reusability** | Can this be reused without modification? |
| **Maintenance Cost** | How hard will this be to reason about in 6 months? |
### Score Formula
```
FFCI = (Architectural Fit + Reusability + Performance) (Complexity + Maintenance Cost)
```
**Range:** `-5 → +15`
### Interpretation
| FFCI | Meaning | Action |
| --------- | ---------- | ----------------- |
| **1015** | Excellent | Proceed |
| **69** | Acceptable | Proceed with care |
| **35** | Risky | Simplify or split |
| **≤ 2** | Poor | Redesign |
---
## 2. Core Architectural Doctrine (Non-Negotiable)
### 1. Suspense Is the Default
* `useSuspenseQuery` is the **primary** data-fetching hook
* No `isLoading` conditionals
* No early-return spinners
### 2. Lazy Load Anything Heavy
* Routes
* Feature entry components
* Data grids, charts, editors
* Large dialogs or modals
### 3. Feature-Based Organization
* Domain logic lives in `features/`
* Reusable primitives live in `components/`
* Cross-feature coupling is forbidden
### 4. TypeScript Is Strict
* No `any`
* Explicit return types
* `import type` always
* Types are first-class design artifacts
---
## 3. When to Use This Skill
Use **frontend-dev-guidelines** when:
* Creating components or pages
* Adding new features
* Fetching or mutating data
* Setting up routing
* Styling with MUI
* Addressing performance issues
* Reviewing or refactoring frontend code
---
## 4. Quick Start Checklists
### New Component Checklist ### New Component Checklist
Creating a component? Follow this checklist: * [ ] `React.FC<Props>` with explicit props interface
* [ ] Lazy loaded if non-trivial
* [ ] Wrapped in `<SuspenseLoader>`
* [ ] Uses `useSuspenseQuery` for data
* [ ] No early returns
* [ ] Handlers wrapped in `useCallback`
* [ ] Styles inline if <100 lines
* [ ] Default export at bottom
* [ ] Uses `useMuiSnackbar` for feedback
- [ ] Use `React.FC<Props>` pattern with TypeScript ---
- [ ] Lazy load if heavy component: `React.lazy(() => import())`
- [ ] Wrap in `<SuspenseLoader>` for loading states
- [ ] Use `useSuspenseQuery` for data fetching
- [ ] Import aliases: `@/`, `~types`, `~components`, `~features`
- [ ] Styles: Inline if <100 lines, separate file if >100 lines
- [ ] Use `useCallback` for event handlers passed to children
- [ ] Default export at bottom
- [ ] No early returns with loading spinners
- [ ] Use `useMuiSnackbar` for user notifications
### New Feature Checklist ### New Feature Checklist
Creating a feature? Set up this structure: * [ ] Create `features/{feature-name}/`
* [ ] Subdirs: `api/`, `components/`, `hooks/`, `helpers/`, `types/`
- [ ] Create `features/{feature-name}/` directory * [ ] API layer isolated in `api/`
- [ ] Create subdirectories: `api/`, `components/`, `hooks/`, `helpers/`, `types/` * [ ] Public exports via `index.ts`
- [ ] Create API service file: `api/{feature}Api.ts` * [ ] Feature entry lazy loaded
- [ ] Set up TypeScript types in `types/` * [ ] Suspense boundary at feature level
- [ ] Create route in `routes/{feature-name}/index.tsx` * [ ] Route defined under `routes/`
- [ ] Lazy load feature components
- [ ] Use Suspense boundaries
- [ ] Export public API from feature `index.ts`
--- ---
## Import Aliases Quick Reference ## 5. Import Aliases (Required)
| Alias | Resolves To | Example | | Alias | Path |
|-------|-------------|---------| | ------------- | ---------------- |
| `@/` | `src/` | `import { apiClient } from '@/lib/apiClient'` | | `@/` | `src/` |
| `~types` | `src/types` | `import type { User } from '~types/user'` | | `~types` | `src/types` |
| `~components` | `src/components` | `import { SuspenseLoader } from '~components/SuspenseLoader'` | | `~components` | `src/components` |
| `~features` | `src/features` | `import { authApi } from '~features/auth'` | | `~features` | `src/features` |
Defined in: [vite.config.ts](../../vite.config.ts) lines 180-185 Aliases must be used consistently. Relative imports beyond one level are discouraged.
--- ---
## Common Imports Cheatsheet ## 6. Component Standards
```typescript ### Required Structure Order
// React & Lazy Loading
import React, { useState, useCallback, useMemo } from 'react';
const Heavy = React.lazy(() => import('./Heavy'));
// MUI Components 1. Types / Props
import { Box, Paper, Typography, Button, Grid } from '@mui/material'; 2. Hooks
import type { SxProps, Theme } from '@mui/material'; 3. Derived values (`useMemo`)
4. Handlers (`useCallback`)
5. Render
6. Default export
// TanStack Query (Suspense) ### Lazy Loading Pattern
import { useSuspenseQuery, useQueryClient } from '@tanstack/react-query';
// TanStack Router ```ts
import { createFileRoute } from '@tanstack/react-router'; const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
// Project Components
import { SuspenseLoader } from '~components/SuspenseLoader';
// Hooks
import { useAuth } from '@/hooks/useAuth';
import { useMuiSnackbar } from '@/hooks/useMuiSnackbar';
// Types
import type { Post } from '~types/post';
``` ```
--- Always wrapped in `<SuspenseLoader>`.
## Topic Guides
### 🎨 Component Patterns
**Modern React components use:**
- `React.FC<Props>` for type safety
- `React.lazy()` for code splitting
- `SuspenseLoader` for loading states
- Named const + default export pattern
**Key Concepts:**
- Lazy load heavy components (DataGrid, charts, editors)
- Always wrap lazy components in Suspense
- Use SuspenseLoader component (with fade animation)
- Component structure: Props → Hooks → Handlers → Render → Export
**[📖 Complete Guide: resources/component-patterns.md](resources/component-patterns.md)**
--- ---
### 📊 Data Fetching ## 7. Data Fetching Doctrine
**PRIMARY PATTERN: useSuspenseQuery** ### Primary Pattern
- Use with Suspense boundaries
- Cache-first strategy (check grid cache before API)
- Replaces `isLoading` checks
- Type-safe with generics
**API Service Layer:** * `useSuspenseQuery`
- Create `features/{feature}/api/{feature}Api.ts` * Cache-first
- Use `apiClient` axios instance * Typed responses
- Centralized methods per feature
- Route format: `/form/route` (NOT `/api/form/route`)
**[📖 Complete Guide: resources/data-fetching.md](resources/data-fetching.md)** ### Forbidden Patterns
`isLoading`
❌ manual spinners
❌ fetch logic inside components
❌ API calls without feature API layer
### API Layer Rules
* One API file per feature
* No inline axios calls
* No `/api/` prefix in routes
--- ---
### 📁 File Organization ## 8. Routing Standards (TanStack Router)
**features/ vs components/:** * Folder-based routing only
- `features/`: Domain-specific (posts, comments, auth) * Lazy load route components
- `components/`: Truly reusable (SuspenseLoader, CustomAppBar) * Breadcrumb metadata via loaders
**Feature Subdirectories:**
```
features/
my-feature/
api/ # API service layer
components/ # Feature components
hooks/ # Custom hooks
helpers/ # Utility functions
types/ # TypeScript types
```
**[📖 Complete Guide: resources/file-organization.md](resources/file-organization.md)**
---
### 🎨 Styling
**Inline vs Separate:**
- <100 lines: Inline `const styles: Record<string, SxProps<Theme>>`
- >100 lines: Separate `.styles.ts` file
**Primary Method:**
- Use `sx` prop for MUI components
- Type-safe with `SxProps<Theme>`
- Theme access: `(theme) => theme.palette.primary.main`
**MUI v7 Grid:**
```typescript
<Grid size={{ xs: 12, md: 6 }}> // ✅ v7 syntax
<Grid xs={12} md={6}> // ❌ Old syntax
```
**[📖 Complete Guide: resources/styling-guide.md](resources/styling-guide.md)**
---
### 🛣️ Routing
**TanStack Router - Folder-Based:**
- Directory: `routes/my-route/index.tsx`
- Lazy load components
- Use `createFileRoute`
- Breadcrumb data in loader
**Example:**
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { lazy } from 'react';
const MyPage = lazy(() => import('@/features/my-feature/components/MyPage'));
```ts
export const Route = createFileRoute('/my-route/')({ export const Route = createFileRoute('/my-route/')({
component: MyPage, component: MyPage,
loader: () => ({ crumb: 'My Route' }), loader: () => ({ crumb: 'My Route' }),
}); });
``` ```
**[📖 Complete Guide: resources/routing-guide.md](resources/routing-guide.md)**
--- ---
### ⏳ Loading & Error States ## 9. Styling Standards (MUI v7)
**CRITICAL RULE: No Early Returns** ### Inline vs Separate
```typescript * `<100 lines`: inline `sx`
// ❌ NEVER - Causes layout shift * `>100 lines`: `{Component}.styles.ts`
if (isLoading) {
return <LoadingSpinner />;
}
// ✅ ALWAYS - Consistent layout ### Grid Syntax (v7 Only)
<SuspenseLoader>
<Content /> ```tsx
</SuspenseLoader> <Grid size={{ xs: 12, md: 6 }} /> // ✅
<Grid xs={12} md={6} /> // ❌
``` ```
**Why:** Prevents Cumulative Layout Shift (CLS), better UX Theme access must always be type-safe.
**Error Handling:**
- Use `useMuiSnackbar` for user feedback
- NEVER `react-toastify`
- TanStack Query `onError` callbacks
**[📖 Complete Guide: resources/loading-and-error-states.md](resources/loading-and-error-states.md)**
--- ---
### ⚡ Performance ## 10. Loading & Error Handling
**Optimization Patterns:** ### Absolute Rule
- `useMemo`: Expensive computations (filter, sort, map)
- `useCallback`: Event handlers passed to children
- `React.memo`: Expensive components
- Debounced search (300-500ms)
- Memory leak prevention (cleanup in useEffect)
**[📖 Complete Guide: resources/performance.md](resources/performance.md)** ❌ Never return early loaders
✅ Always rely on Suspense boundaries
### User Feedback
* `useMuiSnackbar` only
* No third-party toast libraries
--- ---
### 📘 TypeScript ## 11. Performance Defaults
**Standards:** * `useMemo` for expensive derivations
- Strict mode, no `any` type * `useCallback` for passed handlers
- Explicit return types on functions * `React.memo` for heavy pure components
- Type imports: `import type { User } from '~types/user'` * Debounce search (300500ms)
- Component prop interfaces with JSDoc * Cleanup effects to avoid leaks
**[📖 Complete Guide: resources/typescript-standards.md](resources/typescript-standards.md)** Performance regressions are bugs.
--- ---
### 🔧 Common Patterns ## 12. TypeScript Standards
**Covered Topics:** * Strict mode enabled
- React Hook Form with Zod validation * No implicit `any`
- DataGrid wrapper contracts * Explicit return types
- Dialog component standards * JSDoc on public interfaces
- `useAuth` hook for current user * Types colocated with feature
- Mutation patterns with cache invalidation
**[📖 Complete Guide: resources/common-patterns.md](resources/common-patterns.md)**
--- ---
### 📚 Complete Examples ## 13. Canonical File Structure
**Full working examples:**
- Modern component with all patterns
- Complete feature structure
- API service layer
- Route with lazy loading
- Suspense + useSuspenseQuery
- Form with validation
**[📖 Complete Guide: resources/complete-examples.md](resources/complete-examples.md)**
---
## Navigation Guide
| Need to... | Read this resource |
|------------|-------------------|
| Create a component | [component-patterns.md](resources/component-patterns.md) |
| Fetch data | [data-fetching.md](resources/data-fetching.md) |
| Organize files/folders | [file-organization.md](resources/file-organization.md) |
| Style components | [styling-guide.md](resources/styling-guide.md) |
| Set up routing | [routing-guide.md](resources/routing-guide.md) |
| Handle loading/errors | [loading-and-error-states.md](resources/loading-and-error-states.md) |
| Optimize performance | [performance.md](resources/performance.md) |
| TypeScript types | [typescript-standards.md](resources/typescript-standards.md) |
| Forms/Auth/DataGrid | [common-patterns.md](resources/common-patterns.md) |
| See full examples | [complete-examples.md](resources/complete-examples.md) |
---
## Core Principles
1. **Lazy Load Everything Heavy**: Routes, DataGrid, charts, editors
2. **Suspense for Loading**: Use SuspenseLoader, not early returns
3. **useSuspenseQuery**: Primary data fetching pattern for new code
4. **Features are Organized**: api/, components/, hooks/, helpers/ subdirs
5. **Styles Based on Size**: <100 inline, >100 separate
6. **Import Aliases**: Use @/, ~types, ~components, ~features
7. **No Early Returns**: Prevents layout shift
8. **useMuiSnackbar**: For all user notifications
---
## Quick Reference: File Structure
``` ```
src/ src/
features/ features/
my-feature/ my-feature/
api/ api/
myFeatureApi.ts # API service
components/ components/
MyFeature.tsx # Main component
SubComponent.tsx # Related components
hooks/ hooks/
useMyFeature.ts # Custom hooks
useSuspenseMyFeature.ts # Suspense hooks
helpers/ helpers/
myFeatureHelpers.ts # Utilities
types/ types/
index.ts # TypeScript types index.ts
index.ts # Public exports
components/ components/
SuspenseLoader/ SuspenseLoader/
SuspenseLoader.tsx # Reusable loader
CustomAppBar/ CustomAppBar/
CustomAppBar.tsx # Reusable app bar
routes/ routes/
my-route/ my-route/
index.tsx # Route component index.tsx
create/
index.tsx # Nested route
``` ```
--- ---
## Modern Component Template (Quick Copy) ## 14. Canonical Component Template
```typescript ```ts
import React, { useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { Box, Paper } from '@mui/material'; import { Box, Paper } from '@mui/material';
import { useSuspenseQuery } from '@tanstack/react-query'; import { useSuspenseQuery } from '@tanstack/react-query';
@@ -361,9 +291,9 @@ interface MyComponentProps {
} }
export const MyComponent: React.FC<MyComponentProps> = ({ id, onAction }) => { export const MyComponent: React.FC<MyComponentProps> = ({ id, onAction }) => {
const [state, setState] = useState<string>(''); const [state, setState] = useState('');
const { data } = useSuspenseQuery({ const { data } = useSuspenseQuery<FeatureData>({
queryKey: ['feature', id], queryKey: ['feature', id],
queryFn: () => featureApi.getFeature(id), queryFn: () => featureApi.getFeature(id),
}); });
@@ -385,15 +315,45 @@ export const MyComponent: React.FC<MyComponentProps> = ({ id, onAction }) => {
export default MyComponent; export default MyComponent;
``` ```
For complete examples, see [resources/complete-examples.md](resources/complete-examples.md) ---
## 15. Anti-Patterns (Immediate Rejection)
❌ Early loading returns
❌ Feature logic in `components/`
❌ Shared state via prop drilling instead of hooks
❌ Inline API calls
❌ Untyped responses
❌ Multiple responsibilities in one component
--- ---
## Related Skills ## 16. Integration With Other Skills
- **error-tracking**: Error tracking with Sentry (applies to frontend too) * **frontend-design** → Visual systems & aesthetics
- **backend-dev-guidelines**: Backend API patterns that frontend consumes * **page-cro** → Layout hierarchy & conversion logic
* **analytics-tracking** → Event instrumentation
* **backend-dev-guidelines** → API contract alignment
* **error-tracking** → Runtime observability
--- ---
**Skill Status**: Modular structure with progressive loading for optimal context management ## 17. Operator Validation Checklist
Before finalizing code:
* [ ] FFCI ≥ 6
* [ ] Suspense used correctly
* [ ] Feature boundaries respected
* [ ] No early returns
* [ ] Types explicit and correct
* [ ] Lazy loading applied
* [ ] Performance safe
---
## 18. Skill Status
**Status:** Stable, opinionated, and enforceable
**Intended Use:** Production React codebases with long-term maintenance horizons