Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(eslint): add presentational-component lint rule (#494)

Cindy Zhang94262b57440e
diff --git a/internal/eslint-plugin-xds/README.md b/internal/eslint-plugin-xds/README.md
index 195b714465..fce97c3203 100644
--- a/internal/eslint-plugin-xds/README.md
+++ b/internal/eslint-plugin-xds/README.md
@@ -6,10 +6,10 @@ ESLint plugin for XDS design system token enforcement.
This plugin implements a two-tier linting strategy:
-| Mode | Audience | Behavior | Trigger |
-|------|----------|----------|---------|
-| **Recommended** | Humans | Warnings only | Default (local dev) |
-| **Strict** | Agents/CI | Errors (fail build) | `CI=true` or `XDS_STRICT_LINT=1` |
+| Mode | Audience | Behavior | Trigger |
+| --------------- | --------- | ------------------- | -------------------------------- |
+| **Recommended** | Humans | Warnings only | Default (local dev) |
+| **Strict** | Agents/CI | Errors (fail build) | `CI=true` or `XDS_STRICT_LINT=1` |
### Why Two Tiers?
@@ -22,32 +22,34 @@ This plugin implements a two-tier linting strategy:
Detects hardcoded CSS values in `stylex.create()` that should use XDS tokens:
-| Property | Should Use |
-|----------|------------|
-| `fontSize` | `textSizeVars['--text-*']` |
-| `fontWeight` | `fontWeightVars['--font-weight-*']` |
-| `color`, `backgroundColor` | `colorVars['--color-*']` |
-| `padding*`, `margin*`, `gap` | `spacingVars['--spacing-*']` |
-| `borderRadius` | `radiusVars['--radius-*']` |
+| Property | Should Use |
+| ---------------------------- | ----------------------------------- |
+| `fontSize` | `textSizeVars['--text-*']` |
+| `fontWeight` | `fontWeightVars['--font-weight-*']` |
+| `color`, `backgroundColor` | `colorVars['--color-*']` |
+| `padding*`, `margin*`, `gap` | `spacingVars['--spacing-*']` |
+| `borderRadius` | `radiusVars['--radius-*']` |
**Bad:**
+
```tsx
const styles = stylex.create({
text: {
- fontSize: '14px', // ❌ Hardcoded
- fontWeight: 600, // ❌ Hardcoded
- color: '#FF0000', // ❌ Hardcoded
+ fontSize: '14px', // ❌ Hardcoded
+ fontWeight: 600, // ❌ Hardcoded
+ color: '#FF0000', // ❌ Hardcoded
},
});
```
**Good:**
+
```tsx
const styles = stylex.create({
text: {
- fontSize: textSizeVars['--text-base'], // ✅ Token
+ fontSize: textSizeVars['--text-base'], // ✅ Token
fontWeight: fontWeightVars['--font-weight-semibold'], // ✅ Token
- color: colorVars['--color-negative'], // ✅ Token
+ color: colorVars['--color-negative'], // ✅ Token
},
});
```
@@ -94,6 +96,7 @@ yarn lint:strict packages/core/src/Badge/XDSBadge.test-violations.tsx
```
Expected output in strict mode:
+
```
12:15 error Use textSizeVars token instead of hardcoded fontSize @xds/no-hardcoded-styles
17:16 error Use fontWeightVars token instead of hardcoded fontWeight @xds/no-hardcoded-styles
@@ -134,3 +137,49 @@ If a property legitimately needs a hardcoded value:
},
}
```
+
+### `@xds/presentational-component`
+
+Enforces that presentational components remain server-component compatible by preventing:
+
+1. **Remembering things** — `useState`, `useReducer`, `useTransition`
+2. **Watching things** — `useEffect`, `useLayoutEffect`, `useRef`, `ResizeObserver`, etc.
+3. **Coordinating children** — `createContext`
+
+Allowed hooks: `useId`, `useMemo`, `useCallback`, `useContext` (read-only).
+
+**Applies to these components:**
+
+- AspectRatio, Badge, Card, Center, Divider, EmptyState, Field, FormLayout
+- Grid, Layout, Link, NavIcon, ProgressBar, Section, Skeleton, Stack, StatusDot, Token
+
+**Bad:**
+
+```tsx
+// In XDSBadge.tsx
+import {useState} from 'react';
+export function XDSBadge() {
+ const [x, setX] = useState(0); // ❌ Presentational components must not remember things
+ return <span>{x}</span>;
+}
+```
+
+**Good:**
+
+```tsx
+// In XDSBadge.tsx
+import {useId, useContext} from 'react';
+export function XDSBadge({label}) {
+ const id = useId(); // ✅ useId is RSC-compatible
+ const theme = useContext(ThemeContext); // ✅ Reading context is fine
+ return <span id={id}>{label}</span>;
+}
+```
+
+**What to do when you need state/effects:**
+
+- Move the behavior to a wrapper component (e.g. `XDSTextTruncation` wraps `XDSText`)
+- Make state controlled via props (consumer owns the state)
+- If the component legitimately needs client behavior, remove it from the presentational list
+
+See: https://github.com/facebookexperimental/xds/issues/493
diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.js
index ed9c3efc1f..811003527a 100644
--- a/internal/eslint-plugin-xds/index.js
+++ b/internal/eslint-plugin-xds/index.js
@@ -13,6 +13,7 @@
*/
import booleanPropNamingRule from './boolean-prop-naming.js';
+import presentationalComponentRule from './presentational-component.js';
import docblockExampleFormatRule from './docblock-example-format.js';
// =============================================================================
@@ -215,6 +216,7 @@ const plugin = {
rules: {
'no-hardcoded-styles': noHardcodedStylesRule,
'boolean-prop-naming': booleanPropNamingRule,
+ 'presentational-component': presentationalComponentRule,
'docblock-example-format': docblockExampleFormatRule,
},
configs: {},
@@ -228,6 +230,7 @@ plugin.configs.strict = {
rules: {
'@xds/no-hardcoded-styles': 'error',
'@xds/boolean-prop-naming': 'error',
+ '@xds/presentational-component': 'error',
'@xds/docblock-example-format': 'error',
},
};
@@ -240,6 +243,7 @@ plugin.configs.recommended = {
rules: {
'@xds/no-hardcoded-styles': 'warn',
'@xds/boolean-prop-naming': 'warn',
+ '@xds/presentational-component': 'error',
'@xds/docblock-example-format': 'warn',
},
};
diff --git a/internal/eslint-plugin-xds/presentational-component.js b/internal/eslint-plugin-xds/presentational-component.js
new file mode 100644
index 0000000000..a219894874
--- /dev/null
+++ b/internal/eslint-plugin-xds/presentational-component.js
@@ -0,0 +1,170 @@
+/**
+ * @file presentational-component.js
+ * @description ESLint rule enforcing presentational component constraints.
+ *
+ * Presentational components must not:
+ * 1. Remember things — no useState, useReducer, useTransition
+ * 2. Watch things — no useEffect, useLayoutEffect, useRef, ResizeObserver, etc.
+ * 3. Boss children around — no createContext
+ *
+ * Applied to components listed in PRESENTATIONAL_COMPONENTS.
+ * useId, useMemo, useCallback, useContext (read-only) are allowed.
+ *
+ * See: https://github.com/facebookexperimental/xds/issues/493
+ */
+
+/**
+ * Components that must remain presentational.
+ * A component is presentational if: same props → same output, always.
+ * It never remembers, watches, or coordinates on its own.
+ */
+const PRESENTATIONAL_COMPONENTS = new Set([
+ 'XDSAspectRatio',
+ 'XDSBadge',
+ 'XDSCard',
+ 'XDSCenter',
+ 'XDSDivider',
+ 'XDSEmptyState',
+ 'XDSField',
+ 'XDSFormLayout',
+ 'XDSGrid',
+ 'XDSLayout',
+ 'XDSLink',
+ 'XDSNavIcon',
+ 'XDSProgressBar',
+ 'XDSSection',
+ 'XDSSkeleton',
+ 'XDSStack',
+ 'XDSStatusDot',
+ 'XDSToken',
+]);
+
+/**
+ * Hooks that mean the component "remembers" things.
+ */
+const REMEMBERS = new Set([
+ 'useState',
+ 'useReducer',
+ 'useTransition',
+ 'useDeferredValue',
+ 'useOptimistic',
+]);
+
+/**
+ * Hooks/APIs that mean the component "watches" things.
+ * useRef is included because in practice it's used for DOM observation.
+ */
+const WATCHES = new Set([
+ 'useEffect',
+ 'useLayoutEffect',
+ 'useInsertionEffect',
+ 'useRef',
+ 'ResizeObserver',
+ 'IntersectionObserver',
+ 'MutationObserver',
+ 'requestAnimationFrame',
+ 'requestIdleCallback',
+]);
+
+/**
+ * APIs that mean the component "bosses children around".
+ */
+const COORDINATES = new Set([
+ 'createContext',
+]);
+
+/**
+ * Get the filename without path or extension.
+ */
+function getFileStem(filename) {
+ return filename.split('/').pop().replace(/\.(tsx?|jsx?)$/, '');
+}
+
+/**
+ * Check if the current file is a presentational component file.
+ */
+function isPresentationalFile(filename) {
+ const stem = getFileStem(filename);
+ return PRESENTATIONAL_COMPONENTS.has(stem);
+}
+
+const presentationalComponentRule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Prevent presentational components from remembering, watching, or coordinating',
+ category: 'XDS Architecture',
+ recommended: true,
+ url: 'https://github.com/facebookexperimental/xds/issues/493',
+ },
+ messages: {
+ remembers:
+ "'{{name}}' makes {{component}} stateful. Presentational components must not remember things. " +
+ 'Move state to the consumer or a wrapper component.',
+ watches:
+ "'{{name}}' makes {{component}} observe the environment. Presentational components must not watch things. " +
+ 'Move observation to a wrapper component (e.g. XDS{{shortName}}Wrapper).',
+ coordinates:
+ "'{{name}}' makes {{component}} coordinate its children. Presentational components must not boss children around. ' +" +
+ 'Move coordination to a dedicated compound component.',
+ },
+ schema: [],
+ },
+ create(context) {
+ const filename = context.getFilename();
+
+ if (!isPresentationalFile(filename)) {
+ return {};
+ }
+
+ const componentName = getFileStem(filename);
+ const shortName = componentName.replace(/^XDS/, '');
+
+ function report(node, name, category) {
+ context.report({
+ node,
+ messageId: category,
+ data: {name, component: componentName, shortName},
+ });
+ }
+
+ return {
+ // Catch hook calls: useState(), useEffect(), createContext(), etc.
+ CallExpression(node) {
+ const callee = node.callee;
+
+ // Direct call: useState(), createContext()
+ if (callee.type === 'Identifier') {
+ const name = callee.name;
+ if (REMEMBERS.has(name)) report(node, name, 'remembers');
+ else if (WATCHES.has(name)) report(node, name, 'watches');
+ else if (COORDINATES.has(name)) report(node, name, 'coordinates');
+ }
+
+ // Member call: React.useState(), React.createContext()
+ if (
+ callee.type === 'MemberExpression' &&
+ callee.object?.name === 'React'
+ ) {
+ const name = callee.property?.name;
+ if (!name) return;
+ if (REMEMBERS.has(name)) report(node, `React.${name}`, 'remembers');
+ else if (WATCHES.has(name)) report(node, `React.${name}`, 'watches');
+ else if (COORDINATES.has(name))
+ report(node, `React.${name}`, 'coordinates');
+ }
+ },
+
+ // Catch `new ResizeObserver()`, `new IntersectionObserver()`, etc.
+ NewExpression(node) {
+ const name = node.callee?.name;
+ if (name && WATCHES.has(name)) {
+ report(node, name, 'watches');
+ }
+ },
+ };
+ },
+};
+
+export default presentationalComponentRule;
diff --git a/internal/eslint-plugin-xds/presentational-component.test.mjs b/internal/eslint-plugin-xds/presentational-component.test.mjs
new file mode 100644
index 0000000000..d2d4c6c81e
--- /dev/null
+++ b/internal/eslint-plugin-xds/presentational-component.test.mjs
@@ -0,0 +1,167 @@
+/**
+ * @file presentational-component.test.mjs
+ * Tests for the presentational-component ESLint rule
+ */
+
+import {RuleTester} from 'eslint';
+import presentationalComponentRule from './presentational-component.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ parserOptions: {
+ ecmaFeatures: {jsx: true},
+ },
+ },
+});
+
+ruleTester.run('presentational-component', presentationalComponentRule, {
+ valid: [
+ // Non-presentational component — anything goes
+ {
+ code: `
+ import {useState} from 'react';
+ export function XDSButton() {
+ const [x, setX] = useState(0);
+ return <button>{x}</button>;
+ }
+ `,
+ filename: 'packages/core/src/Button/XDSButton.tsx',
+ },
+ // Presentational component — allowed hooks (useId, useMemo, useCallback, useContext)
+ {
+ code: `
+ import {useId, useMemo, useCallback, useContext} from 'react';
+ export function XDSBadge({label}) {
+ const id = useId();
+ const style = useMemo(() => ({}), []);
+ const handler = useCallback(() => {}, []);
+ const theme = useContext(ThemeContext);
+ return <span id={id}>{label}</span>;
+ }
+ `,
+ filename: 'packages/core/src/Badge/XDSBadge.tsx',
+ },
+ // Presentational component — no hooks at all
+ {
+ code: `
+ export function XDSStatusDot({color}) {
+ return <span style={{backgroundColor: color}} />;
+ }
+ `,
+ filename: 'packages/core/src/StatusDot/XDSStatusDot.tsx',
+ },
+ // File not in presentational list — anything goes
+ {
+ code: `
+ import {useState, useEffect, createContext} from 'react';
+ export function XDSTable() {
+ const [data, setData] = useState([]);
+ useEffect(() => {}, []);
+ return <table />;
+ }
+ `,
+ filename: 'packages/core/src/Table/XDSTable.tsx',
+ },
+ ],
+ invalid: [
+ // useState in presentational component
+ {
+ code: `
+ import {useState} from 'react';
+ export function XDSBadge() {
+ const [x, setX] = useState(0);
+ return <span>{x}</span>;
+ }
+ `,
+ filename: 'packages/core/src/Badge/XDSBadge.tsx',
+ errors: [{messageId: 'remembers'}],
+ },
+ // useReducer in presentational component
+ {
+ code: `
+ import {useReducer} from 'react';
+ export function XDSCard() {
+ const [state, dispatch] = useReducer(reducer, {});
+ return <div>{state.value}</div>;
+ }
+ `,
+ filename: 'packages/core/src/Card/XDSCard.tsx',
+ errors: [{messageId: 'remembers'}],
+ },
+ // useTransition in presentational component
+ {
+ code: `
+ import {useTransition} from 'react';
+ export function XDSToken() {
+ const [isPending, startTransition] = useTransition();
+ return <span>{isPending ? 'loading' : 'done'}</span>;
+ }
+ `,
+ filename: 'packages/core/src/Token/XDSToken.tsx',
+ errors: [{messageId: 'remembers'}],
+ },
+ // useEffect in presentational component
+ {
+ code: `
+ import {useEffect} from 'react';
+ export function XDSDivider() {
+ useEffect(() => console.log('mounted'), []);
+ return <hr />;
+ }
+ `,
+ filename: 'packages/core/src/Divider/XDSDivider.tsx',
+ errors: [{messageId: 'watches'}],
+ },
+ // useRef in presentational component
+ {
+ code: `
+ import {useRef} from 'react';
+ export function XDSGrid() {
+ const ref = useRef(null);
+ return <div ref={ref} />;
+ }
+ `,
+ filename: 'packages/core/src/Grid/XDSGrid.tsx',
+ errors: [{messageId: 'watches'}],
+ },
+ // ResizeObserver in presentational component
+ {
+ code: `
+ export function XDSStack() {
+ const observer = new ResizeObserver(() => {});
+ return <div />;
+ }
+ `,
+ filename: 'packages/core/src/Stack/XDSStack.tsx',
+ errors: [{messageId: 'watches'}],
+ },
+ // createContext in presentational component
+ {
+ code: `
+ import {createContext} from 'react';
+ const MyContext = createContext(null);
+ export function XDSSection() {
+ return <MyContext.Provider value={{}}><div /></MyContext.Provider>;
+ }
+ `,
+ filename: 'packages/core/src/Section/XDSSection.tsx',
+ errors: [{messageId: 'coordinates'}],
+ },
+ // React.useState form
+ {
+ code: `
+ import React from 'react';
+ export function XDSCenter() {
+ const [x, setX] = React.useState(0);
+ return <div>{x}</div>;
+ }
+ `,
+ filename: 'packages/core/src/Center/XDSCenter.tsx',
+ errors: [{messageId: 'remembers'}],
+ },
+ ],
+});
+
+console.log('✓ presentational-component rule tests passed');