agentleFS
AlessandroMartiniAlessandroMartini/Awesome_IA_Rules/.cursor/rules/frontend/node-react-frontend.mdc

Awesome_IA_Rules / frontend

Cursor rule1 starsChanged 3 days agoMITView on GitHub

React, TypeScript, and SSR frontend architecture, custom hooks, AsyncState, WCAG 2.1 AA accessibility, BEM/SCSS, and testing

The file

Show its rules and text

We split this node-react-frontend.mdc into the rules it gives an agent

16 rules. About 0 are common, 3 are distinctive, and 13 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 13

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Shared Promotion: If a component or hook is needed by 2+ features, promote it to app/shared/ with comprehensive tests and generic types.

    line 52
  2. Very specific:

    150-Line Limit: Keep components under 150 lines.

    line 59
  3. Distinctive:

    One Component Per File: Never declare multiple stateful components in the same file.

    line 60
  4. Distinctive:

    Every functional component must follow this exact 6-step internal ordering:

    line 63
  5. Very specific:

    Effect Cleanup: Avoid manual useEffect data fetching whenever TanStack Query applies.

    line 126
  6. Very specific:

    Keep server route handlers (getServerSideProps / Server Components / Loaders) thin: verify authentication from the server request context, …

    line 133
  7. Very specific:

    Never access window, document, or localStorage during render without an SSR guard or useEffect, and never render non-deterministic values …

    line 134
  8. Very specific:

    Never use dangerouslySetInnerHTML with unsanitized content.

    line 136
  9. Distinctive:

    Never instantiate inline object/array literals or anonymous closures as props to memoized children.

    line 138
  10. Very specific:

    Use code-splitting (React.lazy / dynamic imports) at feature and route boundaries.

    line 139
  11. Very specific:

    Semantic HTML First: Use <main>, <nav>, <section>, <article>, <button type="button">, and <dialog> instead of generic <div> or <span> …

    line 146
  12. Very specific:

    Keyboard & Focus Management: Ensure all interactive elements are reachable via Tab, operable via Enter/Space/Escape, have visible …

    line 147
  13. Very specific:

    Full Class Names (No &__ Concatenation): Write complete BEM class names (.order-summary__title) instead of nested &__title concatenation …

    line 151
  14. Very specific:

    Contextual Breakpoints: Place responsive media queries/mixins (@include mobile-only, @include tablet-up) directly inside the class rule …

    line 152
  15. Very specific:

    AAA + Builder Pattern: Follow Arrange, Act, Assert (single Act per test) using fluent Builders (new …

    line 158
  16. Very specific:

    Test successful fetch, select transformation, disabled state when params are invalid, and error state handling.

    line 164

≈ “Common” is an estimate: at least 1 in 5 of the 6,668 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
node-react-frontend.mdc
---
description: "React, TypeScript, and SSR frontend architecture, custom hooks, AsyncState, WCAG 2.1 AA accessibility, BEM/SCSS, and testing"
globs: "{app,web,client,frontend,src}/**/*.{ts,tsx,scss,css}"
alwaysApply: false
---

# Frontend Engineering Standards (React, TypeScript & SSR)

> **Scope**: All Frontend TypeScript/React, SSR, and stylesheet files (`{app,web,client,frontend,src}/**/*.{ts,tsx,scss,css}`).
> **Mandate**: Build accessible (WCAG 2.1 AA), high-performance, type-safe, feature-isolated web applications with strict separation between declarative UI Views and custom Hooks.

---

## 1. Feature-Based Architecture

Organize the frontend into self-contained business features under `app/features/` (or `src/features/`). Enforce strict boundaries: **`Pages / Routes (SSR) → Feature View → Custom Hooks → Sub-Components`**.

```text
app/
├── features/                       # Self-contained business features
│   └── {feature-name}/
│       ├── components/             # Feature-scoped sub-components
│       │   └── {SubComponent}/
│       │       ├── hooks/          # Component-specific logic hooks
│       │       ├── {SubComponent}.tsx
│       │       ├── {SubComponent}.types.ts
│       │       ├── {SubComponent}.spec.tsx
│       │       └── index.ts
│       ├── hooks/                  # Feature-level data fetching & domain logic hooks
│       │   └── use{Feature}Data/
│       │       ├── use{Feature}Data.ts
│       │       ├── use{Feature}Data.types.ts
│       │       ├── use{Feature}Data.spec.tsx
│       │       └── index.ts
│       ├── services/               # Typed BFF/API client functions
│       ├── view/                   # Main Feature View (entry UI for pages/MFE)
│       │   ├── {Feature}View.tsx
│       │   ├── {Feature}View.types.ts
│       │   ├── {Feature}View.styles.scss
│       │   └── index.ts
│       └── index.ts                # Feature Public API (export only View & public types)
├── pages/                          # Routing & SSR layer (Next.js / Remix / Custom SSR)
├── shared/                         # Truly global UI primitives, hooks, and utilities
│   ├── components/                 # e.g., AsyncState, ErrorBoundary, QueryClientWrapper
│   └── hooks/
└── styles/                         # Design tokens, breakpoints, global resets
```

### Feature Isolation Rules
- **No Cross-Feature Internal Imports**: Feature A must **never** import internal components or hooks from `features/feature-b/components/*`.
- **Public API Only**: Pages and host containers import exclusively from the feature's public entrypoint (`features/{feature-name}/view` or `features/{feature-name}`).
- **Shared Promotion**: If a component or hook is needed by 2+ features, promote it to `app/shared/` with comprehensive tests and generic types.

---

## 2. Component & Hook Design Standards

### Size & Single Responsibility
- **150-Line Limit**: Keep components under **150 lines**. Extract stateful orchestration, data transformations, and side effects into custom hooks (`hooks/use*.ts`).
- **One Component Per File**: Never declare multiple stateful components in the same file.

### Canonical Component Organization Order
Every functional component must follow this exact 6-step internal ordering:

```tsx
export const OrderSummaryView: FC<OrderSummaryViewProps> = (props) => {
  // 1. Destructure props (with defaults)
  const { orderId, isCompact = false, onOrderCancel } = props;

  // 2. Custom hooks (server state, i18n, feature logic)
  const { data, isLoading, isError, refetch } = useOrderSummaryData({ orderId });

  // 3. Derived state (useMemo)
  const formattedTotal = useMemo(() => formatCurrency(data?.total), [data?.total]);

  // 4. Event handlers (useCallback)
  const handleCancelClick = useCallback(() => {
    onOrderCancel?.(orderId);
  }, [onOrderCancel, orderId]);

  // 5. Declarative AsyncState / Conditional early returns (Loading / Error / Empty)
  return (
    <AsyncState
      isLoading={isLoading}
      isError={isError}
      isEmpty={!data}
      skeleton={<OrderSummarySkeleton />}
      onRetry={refetch}
    >
      {/* 6. Main render */}
      <section className="order-summary" aria-labelledby="order-summary-title">
        <h2 id="order-summary-title" className="order-summary__title">
          {data?.title}
        </h2>
        <span className="order-summary__total">{formattedTotal}</span>
        {!isCompact && (
          <button
            type="button"
            className="order-summary__cancel-button"
            onClick={handleCancelClick}
          >
            Cancel Order
          </button>
        )}
      </section>
    </AsyncState>
  );
};
```

### Server State & Data Fetching (TanStack Query / React Query)
- **Scalable `select` Pattern**: Expose a generic `select?: (data: TDomain) => TSelected` parameter in data-fetching hooks so consumer components subscribe only to the slice of data they render, minimizing re-renders:
  ```typescript
  export const useFetchOrder = <TData = OrderData>({
    orderId,
    select,
  }: UseFetchOrderParams<TData>) => {
    return useQuery<OrderData, Error, TData>({
      queryKey: orderKeys.byId(orderId),
      queryFn: ({ signal }) => getOrderById(orderId, { signal }),
      enabled: Boolean(orderId),
      select,
    });
  };
  ```
- **Effect Cleanup**: Avoid manual `useEffect` data fetching whenever TanStack Query applies. When `useEffect` is required for subscriptions or DOM events, **always** return a cleanup function (`AbortController.abort()`, `isCancelled = true`, `removeEventListener`) to prevent memory leaks and state updates on unmounted components.

---

## 3. SSR, Security & Performance

- **SSR & Hydration Safety**:
  - Keep server route handlers (`getServerSideProps` / Server Components / Loaders) thin: verify authentication from the server request context, validate route params, and pass only minimal, sanitized props to the client.
  - Never access `window`, `document`, or `localStorage` during render without an SSR guard or `useEffect`, and never render non-deterministic values (`Date.now()`, `Math.random()`) that cause SSR/CSR hydration mismatches.
- **XSS Prevention**:
  - Never use `dangerouslySetInnerHTML` with unsanitized content. When rendering rich text is unavoidable, sanitize with **DOMPurify** (`RETURN_TRUSTED_TYPE: true`).
- **Performance**:
  - Never instantiate inline object/array literals or anonymous closures as props to memoized children.
  - Use code-splitting (`React.lazy` / dynamic imports) at feature and route boundaries.

---

## 4. Accessibility (WCAG 2.1 AA) & Styling (SCSS / BEM)

### Accessibility (a11y)
- **Semantic HTML First**: Use `<main>`, `<nav>`, `<section>`, `<article>`, `<button type="button">`, and `<dialog>` instead of generic `<div>` or `<span>` elements with click handlers.
- **Keyboard & Focus Management**: Ensure all interactive elements are reachable via `Tab`, operable via `Enter`/`Space`/`Escape`, have visible `:focus-visible` outlines, and trap/restore focus properly in modals/drawers.
- **ARIA & Contrast**: Provide `aria-label` or `aria-labelledby` for icon/control elements, `aria-invalid` + `aria-describedby` (`role="alert"`) for form validation errors, and maintain a minimum `4.5:1` text contrast ratio.

### Searchable BEM & Contextual Responsive Styling
- **Full Class Names (No `&__` Concatenation)**: Write complete BEM class names (`.order-summary__title`) instead of nested `&__title` concatenation so every class name is 100% greppable with `Ctrl+F` / `ripgrep`. Use `&` **only** for pseudo-classes (`&:hover`, `&:focus-visible`) and modifiers (`&--compact`).
- **Contextual Breakpoints**: Place responsive media queries/mixins (`@include mobile-only`, `@include tablet-up`) directly inside the class rule they modify, never in a detached block at the bottom of the file. Use design-system CSS custom properties (`var(--color-surface-primary)`) instead of hardcoded hex values.

---

## 5. Frontend Testing (`*.spec.tsx`)

- **AAA + Builder Pattern**: Follow **Arrange, Act, Assert** (single Act per test) using fluent **Builders** (`new OrderDataBuilder().withPendingStatus().build()`) for all mock data.
- **Component Tests (React Testing Library)**:
  - Query the DOM the way a user interacts with it (`screen.getByRole`, `screen.getByLabelText`, `screen.getByText`); use `data-testid` only as a last resort.
  - Explicitly test all 4 visual states: **Loading (skeleton)**, **Success**, **Empty**, and **Error (with retry interaction)**.
- **Hook Tests (`renderHook`)**:
  - Wrap React Query hooks in a clean `TestQueryClientWrapper` (with `retry: false`).
  - Test successful fetch, `select` transformation, disabled state when params are invalid, and error state handling.
- **Coverage Target**: `>= 90%` across feature components, custom hooks, and shared utilities.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.