An open source design system that's fully customizable and agent ready
TypeScript
feat(lint): add no-react-namespace-hooks rule and fix violations (#2196)
Andrey Goder251275b2bacf
diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.jsindex 5327b005e2..f5c5f0dd4e 100644--- a/internal/eslint-plugin-xds/index.js+++ b/internal/eslint-plugin-xds/index.js@@ -20,6 +20,7 @@ import noReactIntrospectionRule from './no-react-introspection.js';import noClassnameClobberRule from './no-classname-clobber.js';import noHardcodedAnchorRule from './no-hardcoded-anchor.js';import noBorderShorthandRule from './no-border-shorthand.js';+import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';// =============================================================================// Rule: no-hardcoded-styles@@ -228,6 +229,7 @@ const plugin = {'no-classname-clobber': noClassnameClobberRule,'no-hardcoded-anchor': noHardcodedAnchorRule,'no-border-shorthand': noBorderShorthandRule,+ 'no-react-namespace-hooks': noReactNamespaceHooksRule,},configs: {},};@@ -247,6 +249,7 @@ plugin.configs.strict = {'@xds/no-classname-clobber': 'error','@xds/no-hardcoded-anchor': 'error','@xds/no-border-shorthand': 'error',+ '@xds/no-react-namespace-hooks': 'error',},};@@ -265,6 +268,7 @@ plugin.configs.recommended = {'@xds/no-classname-clobber': 'error','@xds/no-hardcoded-anchor': 'warn','@xds/no-border-shorthand': 'warn',+ '@xds/no-react-namespace-hooks': 'error',},};diff --git a/internal/eslint-plugin-xds/no-react-namespace-hooks.js b/internal/eslint-plugin-xds/no-react-namespace-hooks.jsnew file mode 100644index 0000000000..c6c3ee5dde--- /dev/null+++ b/internal/eslint-plugin-xds/no-react-namespace-hooks.js@@ -0,0 +1,77 @@+/**+ * @file no-react-namespace-hooks.js+ * @description ESLint rule requiring direct imports of React hooks+ * instead of accessing them via the React namespace.+ *+ * Prefer: import { useEffect } from 'react'; useEffect(...)+ * Avoid: import React from 'react'; React.useEffect(...)+ *+ * This keeps imports explicit and consistent across the codebase.+ */++const REACT_HOOKS = new Set([+ 'useState',+ 'useEffect',+ 'useContext',+ 'useReducer',+ 'useCallback',+ 'useMemo',+ 'useRef',+ 'useImperativeHandle',+ 'useLayoutEffect',+ 'useInsertionEffect',+ 'useDebugValue',+ 'useDeferredValue',+ 'useTransition',+ 'useId',+ 'useSyncExternalStore',+ 'useActionState',+ 'useOptimistic',+ 'useFormStatus',+]);++const noReactNamespaceHooksRule = {+ meta: {+ type: 'suggestion',+ docs: {+ description:+ 'Require direct imports of React hooks instead of React.useX() namespace access',+ category: 'XDS Conventions',+ recommended: true,+ },+ fixable: 'code',+ messages: {+ noNamespaceHook:+ 'Use a direct import instead of React.{{hook}}(). ' ++ "Import { {{hook}} } from 'react' and call {{hook}}() directly.",+ },+ schema: [],+ },+ create(context) {+ return {+ CallExpression(node) {+ const callee = node.callee;+ if (+ callee.type === 'MemberExpression' &&+ !callee.computed &&+ callee.object.type === 'Identifier' &&+ callee.object.name === 'React' &&+ callee.property.type === 'Identifier' &&+ REACT_HOOKS.has(callee.property.name)+ ) {+ const hook = callee.property.name;+ context.report({+ node: callee,+ messageId: 'noNamespaceHook',+ data: {hook},+ fix(fixer) {+ return fixer.replaceText(callee, hook);+ },+ });+ }+ },+ };+ },+};++export default noReactNamespaceHooksRule;diff --git a/internal/eslint-plugin-xds/no-react-namespace-hooks.test.mjs b/internal/eslint-plugin-xds/no-react-namespace-hooks.test.mjsnew file mode 100644index 0000000000..72e4ff6665--- /dev/null+++ b/internal/eslint-plugin-xds/no-react-namespace-hooks.test.mjs@@ -0,0 +1,174 @@+/**+ * @file no-react-namespace-hooks.test.mjs+ */++import {RuleTester} from 'eslint';+import rule from './no-react-namespace-hooks.js';++const ruleTester = new RuleTester({+ languageOptions: {+ ecmaVersion: 2022,+ sourceType: 'module',+ parserOptions: {ecmaFeatures: {jsx: true}},+ },+});++ruleTester.run('no-react-namespace-hooks', rule, {+ valid: [+ // Direct import and call+ {+ code: `+ import { useEffect } from 'react';+ useEffect(() => {}, []);+ `,+ },+ // Multiple direct imports+ {+ code: `+ import { useState, useCallback, useMemo } from 'react';+ const [v, setV] = useState(0);+ const cb = useCallback(() => {}, []);+ const m = useMemo(() => v, [v]);+ `,+ },+ // React.createElement is fine (not a hook)+ {+ code: `+ import React from 'react';+ React.createElement('div');+ `,+ },+ // React.forwardRef is fine (not a hook)+ {+ code: `+ import React from 'react';+ React.forwardRef((props, ref) => null);+ `,+ },+ // React.memo is fine (not a hook)+ {+ code: `+ import React from 'react';+ React.memo(() => null);+ `,+ },+ // Custom hook call is fine+ {+ code: `+ import { useMyHook } from './hooks';+ useMyHook();+ `,+ },+ // Non-React namespace is fine+ {+ code: `+ const React = { useEffect: () => {} };+ `,+ },+ ],+ invalid: [+ // React.useEffect+ {+ code: `+ import React from 'react';+ React.useEffect(() => {}, []);+ `,+ output: `+ import React from 'react';+ useEffect(() => {}, []);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useEffect'}}],+ },+ // React.useState+ {+ code: `+ import React from 'react';+ const [v, setV] = React.useState(0);+ `,+ output: `+ import React from 'react';+ const [v, setV] = useState(0);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useState'}}],+ },+ // React.useCallback+ {+ code: `+ import React from 'react';+ const cb = React.useCallback(() => {}, []);+ `,+ output: `+ import React from 'react';+ const cb = useCallback(() => {}, []);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useCallback'}}],+ },+ // React.useMemo+ {+ code: `+ import React from 'react';+ const val = React.useMemo(() => 42, []);+ `,+ output: `+ import React from 'react';+ const val = useMemo(() => 42, []);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useMemo'}}],+ },+ // React.useContext+ {+ code: `+ import React from 'react';+ const ctx = React.useContext(MyContext);+ `,+ output: `+ import React from 'react';+ const ctx = useContext(MyContext);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useContext'}}],+ },+ // React.useRef+ {+ code: `+ import React from 'react';+ const ref = React.useRef(null);+ `,+ output: `+ import React from 'react';+ const ref = useRef(null);+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useRef'}}],+ },+ // React.useId+ {+ code: `+ import React from 'react';+ const id = React.useId();+ `,+ output: `+ import React from 'react';+ const id = useId();+ `,+ errors: [{messageId: 'noNamespaceHook', data: {hook: 'useId'}}],+ },+ // Multiple violations in one file+ {+ code: `+ import React from 'react';+ React.useEffect(() => {}, []);+ React.useState(0);+ `,+ output: `+ import React from 'react';+ useEffect(() => {}, []);+ useState(0);+ `,+ errors: [+ {messageId: 'noNamespaceHook', data: {hook: 'useEffect'}},+ {messageId: 'noNamespaceHook', data: {hook: 'useState'}},+ ],+ },+ ],+});++console.log('All tests passed!');diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsxindex aba6db32e8..eaafe137e1 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx@@ -22,6 +22,7 @@import React, {useCallback,+ useEffect,useId,useMemo,useRef,@@ -242,7 +243,7 @@ export function XDSDropdownMenu({});// Sync controlled open state → popover, and focus first item on open- React.useEffect(() => {+ useEffect(() => {if (isControlled) {if (controlledIsOpen && !popover.isOpen) {popover.show();diff --git a/packages/core/src/Popover/XDSPopover.test.tsx b/packages/core/src/Popover/XDSPopover.test.tsxindex 32e8b1e9b7..192f4f76d0 100644--- a/packages/core/src/Popover/XDSPopover.test.tsx+++ b/packages/core/src/Popover/XDSPopover.test.tsx@@ -9,7 +9,7 @@import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';-import React from 'react';+import React, {useRef} from 'react';import {XDSPopover} from './XDSPopover';// Store original matches to restore later@@ -143,7 +143,7 @@ describe('XDSPopover', () => {it('supports anchorRef sibling mode', () => {function AnchorRefTest() {- const ref = React.useRef<HTMLButtonElement>(null);+ const ref = useRef<HTMLButtonElement>(null);return (<><button ref={ref}>Anchor</button>diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsxindex b2c6efafd7..f6f2102674 100644--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx@@ -585,7 +585,7 @@ export function PowerSearchEditPopover({const valueEditorRef = useRef<HTMLDivElement>(null);// Reset state when filter changes (new popover opened)- React.useEffect(() => {+ useEffect(() => {setPartialFilter(initialFilter);}, [initialFilter]);@@ -704,7 +704,7 @@ export function PowerSearchEditPopover({const isNestedType = operatorValue?.type === 'nested';// For empty type, auto-save on mount- React.useEffect(() => {+ useEffect(() => {if (isEmptyType && partialFilter.field && partialFilter.operator) {onSave({field: partialFilter.field,diff --git a/packages/core/src/TextArea/XDSTextArea.test.tsx b/packages/core/src/TextArea/XDSTextArea.test.tsxindex 2e8f7db0a6..66b395d15c 100644--- a/packages/core/src/TextArea/XDSTextArea.test.tsx+++ b/packages/core/src/TextArea/XDSTextArea.test.tsx@@ -7,7 +7,7 @@* SYNC: When XDSTextArea.tsx changes, update tests to match new behavior*/-import React from 'react';+import {useState} from 'react';import {describe, it, expect, vi} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -464,7 +464,7 @@ describe('XDSTextArea', () => {it('counter updates as user types (controlled)', async () => {const user = userEvent.setup();function Wrapper() {- const [val, setVal] = React.useState('');+ const [val, setVal] = useState('');return (<XDSTextArealabel="Description"diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsxindex ea3a94fe94..94e34b1f51 100644--- a/packages/core/src/theme/XDSTheme.tsx+++ b/packages/core/src/theme/XDSTheme.tsx@@ -32,7 +32,13 @@* ```*/-import React, {useId, useInsertionEffect, useMemo, useRef} from 'react';+import React, {+ useContext,+ useId,+ useInsertionEffect,+ useMemo,+ useRef,+} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';import type {ThemeMode} from './types';@@ -300,7 +306,7 @@ export function XDSTheme({mode = 'system',children,}: XDSThemeProps): React.ReactElement {- const isNested = React.useContext(XDSThemeNestingContext);+ const isNested = useContext(XDSThemeNestingContext);useThemeStyleInjection(theme);useThemeFontLoading(theme);