Cursor rule for composing React components with children, named slots, context-based compound components, custom hooks over wrappers and slots over config props.
.cursor/rules/react-component-composition.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for composing React components with children, named slots, context-based compound components, custom hooks over wrappers and slots over config props."
globs: "**/*"
alwaysApply: false
---
# React Component Composition
Applies to: React components and component libraries where you design props, layout wrappers and reusable UI building blocks.
Version baseline: checked against the React 19 docs. In React 19, `ref` is a regular prop for function components, so `forwardRef` is not needed in new code. Read the project's `react` version in `package.json`. On React 18, keep using `forwardRef`.
## 1. Pass content as children
Layout and container components accept `children` instead of a growing list of content props.
```tsx
import type { ReactNode } from "react";
export function Card({ children }: { children: ReactNode }) {
return <section className="card">{children}</section>;
}
```
## 2. Use named slots for distinct regions
When a component has several regions, accept them as separately named `ReactNode` props.
```tsx
import type { ReactNode } from "react";
type PageLayoutProps = { header: ReactNode; sidebar?: ReactNode; children: ReactNode };
export function PageLayout({ header, sidebar, children }: PageLayoutProps) {
return (
<div className="layout">
<header>{header}</header>
{sidebar ? <aside>{sidebar}</aside> : null}
<main>{children}</main>
</div>
);
}
```
## 3. Compound components for related UI
Use compound components when parts must share state but callers control the markup. Share the state through context, not `React.Children`/`cloneElement`. React's docs list those APIs as uncommon and fragile.
```tsx
import { createContext, use, useId, useState, type ReactNode } from "react";
type TabsState = { active: string; setActive: (v: string) => void; baseId: string };
const TabsContext = createContext<TabsState | null>(null);
function useTabs(): TabsState {
const ctx = use(TabsContext);
if (!ctx) throw new Error("Tabs.* must be used inside <Tabs>");
return ctx;
}
export function Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {
const [active, setActive] = useState(defaultValue);
const baseId = useId();
return <TabsContext value={{ active, setActive, baseId }}>{children}</TabsContext>;
}
Tabs.List = function TabsList({ children }: { children: ReactNode }) {
return <div role="tablist">{children}</div>;
};
Tabs.Tab = function Tab({ value, children }: { value: string; children: ReactNode }) {
const { active, setActive, baseId } = useTabs();
return (
<button type="button" role="tab" id={`${baseId}-tab-${value}`} aria-selected={active === value}
aria-controls={`${baseId}-panel-${value}`} onClick={() => setActive(value)}>
{children}
</button>
);
};
Tabs.Panel = function TabPanel({ value, children }: { value: string; children: ReactNode }) {
const { active, baseId } = useTabs();
return (
<div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`}
hidden={active !== value}>
{children}
</div>
);
};
```
Inactive panels stay in the DOM with `hidden`, so every `aria-controls` points to an existing element. A production tabs widget also needs arrow-key navigation (see the WAI-ARIA APG tabs pattern). `<Context value>` as a provider and `use(Context)` are React 19 APIs; on React 18 use `<TabsContext.Provider>` and `useContext`.
## 4. Share behaviour with custom hooks, not wrappers
- Extract reusable stateful logic into a custom hook (`useDisclosure`, `useDebouncedValue`) that returns values and callbacks. Each caller renders its own markup.
- Use a render prop (`renderItem={(item) => ...}`) only when the component owns iteration or layout but the caller must decide how each item renders, such as virtualised lists or tables. Avoid higher-order components in new code.
## 5. Prefer composition over configuration props
- When a component accumulates boolean or variant props that toggle markup (`showIcon`, `iconPosition`, `hasFooter`, `footerText`), switch to slots or children instead.
- Keep `variant` or `size` props for real visual variants of one element. Do not use them to switch between different structures.
## 6. Keep components focused
- Separate data loading from presentation: a container (or a Server Component in frameworks that support it) loads data and passes plain props to presentational components.
- Split a component when it handles unrelated concerns, or when parts of it re-render for unrelated state changes. Do not split by line count.
- Forward unknown DOM props and `ref` deliberately (`...rest` on the root element) in design-system primitives, and type them with `ComponentPropsWithoutRef<"button">` or similar.
## Verify before finishing
- Type-check (`npx tsc --noEmit`) and run the component tests for each composition path (with and without optional slots).
- Check that context consumers throw a clear error when used outside their provider, and that keyboard and ARIA behaviour of compound widgets is tested.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A design-system or product team asks Cursor to refactor a component that has grown a long list of boolean and content props.
Refactor Panel.tsx, which has props title, showIcon, iconPosition, hasFooter, footerText, footerAlign and tabs: {label, content}[]. Callers need custom footers and custom tab content. React 19.2, TypeScript strict.Illustrative; not a recorded model run. Panel accepts children plus header/footer slots typed as ReactNode, and the boolean/icon/footer props are removed. Tabs become a compound <Tabs>/<Tabs.List>/<Tabs.Tab>/<Tabs.Panel> sharing state through context (React 19 <Context value> and use(), or Provider/useContext on React 18). A hook throws a clear error outside the provider, inactive panels use hidden, and there are no React.Children or cloneElement calls. The answer includes before/after usage at a call site and a note to add APG arrow-key handling.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/react-component-composition.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "React Component Composition: Children, Slots, Compound Components and Hooks project conventions"
globs: "**/*"
alwaysApply: false
---
# React Component Composition
Applies to: React components and component libraries where you design props, layout wrappers and reusable UI building blocks.
Version baseline: checked against the React 19 docs. In React 19, `ref` is a regular prop for function components, so `forwardRef` is not needed in new code. Read the project's `react` version in `package.json`. On React 18, keep using `forwardRef`.
## 1. Pass content as children
Layout and container components accept `children` instead of a growing list of content props.
```tsx
import type { ReactNode } from "react";
export function Card({ children }: { children: ReactNode }) {
return <section className="card">{children}</section>;
}
```
## 2. Use named slots for distinct regions
When a component has several regions, accept them as separately named `ReactNode` props.
```tsx
import type { ReactNode } from "react";
type PageLayoutProps = { header: ReactNode; sidebar?: ReactNode; children: ReactNode };
export function PageLayout({ header, sidebar, children }: PageLayoutProps) {
return (
<div className="layout">
<header>{header}</header>
{sidebar ? <aside>{sidebar}</aside> : null}
<main>{children}</main>
</div>
);
}
```
## 3. Compound components for related UI
Use compound components when parts must share state but callers control the markup. Share the state through context, not `React.Children`/`cloneElement`. React's docs list those APIs as uncommon and fragile.
```tsx
import { createContext, use, useId, useState, type ReactNode } from "react";
type TabsState = { active: string; setActive: (v: string) => void; baseId: string };
const TabsContext = createContext<TabsState | null>(null);
function useTabs(): TabsState {
const ctx = use(TabsContext);
if (!ctx) throw new Error("Tabs.* must be used inside <Tabs>");
return ctx;
}
export function Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {
const [active, setActive] = useState(defaultValue);
const baseId = useId();
return <TabsContext value={{ active, setActive, baseId }}>{children}</TabsContext>;
}
Tabs.List = function TabsList({ children }: { children: ReactNode }) {
return <div role="tablist">{children}</div>;
};
Tabs.Tab = function Tab({ value, children }: { value: string; children: ReactNode }) {
const { active, setActive, baseId } = useTabs();
return (
<button type="button" role="tab" id={`${baseId}-tab-${value}`} aria-selected={active === value}
aria-controls={`${baseId}-panel-${value}`} onClick={() => setActive(value)}>
{children}
</button>
);
};
Tabs.Panel = function TabPanel({ value, children }: { value: string; children: ReactNode }) {
const { active, baseId } = useTabs();
return (
<div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`}
hidden={active !== value}>
{children}
</div>
);
};
```
Inactive panels stay in the DOM with `hidden`, so every `aria-controls` points to an existing element. A production tabs widget also needs arrow-key navigation (see the WAI-ARIA APG tabs pattern). `<Context value>` as a provider and `use(Context)` are React 19 APIs; on React 18 use `<TabsContext.Provider>` and `useContext`.
## 4. Share behaviour with custom hooks, not wrappers
- Extract reusable stateful logic into a custom hook (`useDisclosure`, `useDebouncedValue`) that returns values and callbacks. Each caller renders its own markup.
- Use a render prop (`renderItem={(item) => ...}`) only when the component owns iteration or layout but the caller must decide how each item renders, such as virtualised lists or tables. Avoid higher-order components in new code.
## 5. Prefer composition over configuration props
- When a component accumulates boolean or variant props that toggle markup (`showIcon`, `iconPosition`, `hasFooter`, `footerText`), switch to slots or children instead.
- Keep `variant` or `size` props for real visual variants of one element. Do not use them to switch between different structures.
## 6. Keep components focused
- Separate data loading from presentation: a container (or a Server Component in frameworks that support it) loads data and passes plain props to presentational components.
- Split a component when it handles unrelated concerns, or when parts of it re-render for unrelated state changes. Do not split by line count.
- Forward unknown DOM props and `ref` deliberately (`...rest` on the root element) in design-system primitives, and type them with `ComponentPropsWithoutRef<"button">` or similar.
## Verify before finishing
- Type-check (`npx tsc --noEmit`) and run the component tests for each composition path (with and without optional slots).
- Check that context consumers throw a clear error when used outside their provider, and that keyboard and ARIA behaviour of compound widgets is tested.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.