Skip to content

feat(eslint-plugin-query): add prefer-query-options rule#10359

Open
Newbie012 wants to merge 5 commits intomainfrom
feat-eslint-prefer-query-options
Open

feat(eslint-plugin-query): add prefer-query-options rule#10359
Newbie012 wants to merge 5 commits intomainfrom
feat-eslint-prefer-query-options

Conversation

@Newbie012
Copy link
Copy Markdown
Collaborator

@Newbie012 Newbie012 commented Mar 30, 2026

Prior discussion #8515

🎯 Changes

New ESLint rule prefer-query-options that enforces using queryOptions() / infiniteQueryOptions() to co-locate query keys and functions. A query key should be defined exactly once — the rule flags every place where a user types one manually.

This is rule is stricter and more opinionated than the others, I also createdrecommendedStrict config (flat/recommended-strict) which includes all recommended rules plus this rule.

Examples:

// 🔴 Inline queryKey + queryFn — should use queryOptions()
useQuery({
  queryKey: ['todos'],
  queryFn: () => fetchTodos(),
})

// 🔴 Inline queryKey in queryClient methods
queryClient.getQueryData(['todos'])
queryClient.invalidateQueries({ queryKey: ['todos'] })

// 🟢 Co-located via queryOptions()
const todosOptions = queryOptions({
  queryKey: ['todos'],
  queryFn: () => fetchTodos(),
})

useQuery(todosOptions)
useQuery({ ...todosOptions, select: (data) => data.items })
queryClient.getQueryData(todosOptions.queryKey)
queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features

    • Added an ESLint rule to flag inline query key/function usage and a "Recommended strict" preset that enables it.
  • Documentation

    • Added a comprehensive docs page, examples, and a navigation entry describing the rule and recommended usage.
  • Tests

    • Added extensive test coverage validating correct and incorrect usage patterns.
  • Chores

    • Added a changeset preparing a minor package bump for the new rule.

@github-actions github-actions bot added documentation Improvements or additions to documentation package: eslint-plugin-query labels Mar 30, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 30, 2026

📝 Walkthrough

Walkthrough

Adds a new ESLint rule prefer-query-options with implementation, tests, docs, a changeset, and plugin exports including a recommendedStrict / flat/recommended-strict preset to enable the rule.

Changes

Cohort / File(s) Summary
Release Metadata
\.changeset/prefer-query-options-rule.md
New changeset declaring a minor version bump for @tanstack/eslint-plugin-query and announcing prefer-query-options and recommendedStrict.
Documentation
docs/config.json, docs/eslint/eslint-plugin-query.md, docs/eslint/prefer-query-options.md
Added navigation entry, updated plugin docs with a "Recommended strict" config, and a full rule page describing behavior, examples, and applicability.
Rule Implementation
packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
New ESLint rule that detects inline queryKey/queryFn in TanStack Query hooks and queryClient calls and reports usages that should use queryOptions()/infiniteQueryOptions().
Rule Registration & Exports
packages/eslint-plugin-query/src/rules.ts, packages/eslint-plugin-query/src/index.ts
Registered the new rule in the plugin's rules map and added recommendedStrict and flat/recommended-strict configs (and corresponding Plugin interface entries), referencing shared rule-sets.
Test Suite
packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
Comprehensive RuleTester suite covering valid/invalid cases across hooks, useQueries variants, query client methods, mapping returns, and edge/ignore scenarios.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hop through code with careful eyes,

Keys and functions paired — no compromise.
Inline no more, let options bloom,
Neat queries keep the runtime groomed.
Hooray! A lint that clears the room.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: adding a new ESLint rule called prefer-query-options to the eslint-plugin-query package.
Description check ✅ Passed The description follows the template structure, includes clear examples of the rule behavior, explains motivation, marks both checklist items as complete, and confirms a changeset was generated.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-eslint-prefer-query-options

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud
Copy link
Copy Markdown

nx-cloud bot commented Mar 30, 2026

View your CI Pipeline Execution ↗ for commit 26737a2

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 1m 4s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded <1s View ↗

☁️ Nx Cloud last updated this comment at 2026-03-30 20:26:45 UTC

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 30, 2026

🚀 Changeset Version Preview

1 package(s) bumped directly, 23 bumped as dependents.

🟨 Minor bumps

Package Version Reason
@tanstack/eslint-plugin-query 5.95.2 → 5.96.0 Changeset
@tanstack/angular-query-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/angular-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/preact-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/query-async-storage-persister 5.95.2 → 5.96.0 Dependent
@tanstack/query-broadcast-client-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/query-core 5.95.2 → 5.96.0 Dependent
@tanstack/query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/query-persist-client-core 5.95.2 → 5.96.0 Dependent
@tanstack/query-sync-storage-persister 5.95.2 → 5.96.0 Dependent
@tanstack/react-query 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-next-experimental 5.95.2 → 5.96.0 Dependent
@tanstack/react-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query-devtools 5.95.2 → 5.96.0 Dependent
@tanstack/solid-query-persist-client 5.95.2 → 5.96.0 Dependent
@tanstack/vue-query 5.95.2 → 5.96.0 Dependent

🟩 Patch bumps

Package Version Reason
@tanstack/svelte-query 6.1.10 → 6.1.11 Dependent
@tanstack/svelte-query-devtools 6.1.10 → 6.1.11 Dependent
@tanstack/svelte-query-persist-client 6.1.10 → 6.1.11 Dependent
@tanstack/vue-query-devtools 6.1.10 → 6.1.11 Dependent

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Mar 30, 2026

More templates

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@10359

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@10359

@tanstack/preact-query

npm i https://pkg.pr.new/@tanstack/preact-query@10359

@tanstack/preact-query-devtools

npm i https://pkg.pr.new/@tanstack/preact-query-devtools@10359

@tanstack/preact-query-persist-client

npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@10359

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@10359

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@10359

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@10359

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@10359

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@10359

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@10359

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@10359

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@10359

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@10359

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@10359

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@10359

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@10359

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@10359

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@10359

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@10359

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@10359

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@10359

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@10359

commit: 26737a2

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 30, 2026

size-limit report 📦

Path Size
react full 11.98 KB (0%)
react minimal 9.01 KB (0%)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/eslint/prefer-query-options.md`:
- Around line 27-31: The examples (e.g., useFooQuery and the queryOptions(...)
snippets) reference id without any binding; change them into factory functions
that accept id (e.g., function useFooQuery(id) or export function
queryOptions(id)) and then pass that id into the useQuery call (or into
queryOptions(id)) so the id is in scope; update any example that builds
queryOptions(...) to be queryOptions(id) and update callers to pass the id into
useFooQuery or the options factory accordingly (references: useFooQuery,
queryOptions, options).

In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 23-30: The rule currently only flags inline options for methods in
queryClientOptionMethods but misses the newer APIs; add 'query' and
'infiniteQuery' to the queryClientOptionMethods array so inline options passed
to queryClient.query(...) and queryClient.infiniteQuery(...) are checked, and
update the test suite for this rule to include invalid cases covering query()
and infiniteQuery() (matching the existing invalid cases for
fetchQuery/fetchInfiniteQuery) so the select option behavior is asserted for
both legacy and new APIs; update any test matrix entries that reference method
names to include 'query' and 'infiniteQuery' as well.
- Around line 177-180: The rule currently checks options.type ===
AST_NODE_TYPES.ArrayExpression directly and misses TS assertion wrappers; update
the checks inside the prefer-query-options rule where queryClientQueryKeyMethods
is handled (and inside hasInlineFilterQueryKey) to first unwrap TypeScript
assertion nodes using the existing helper dereferenceVariablesAndTypeAssertions
(as used in exhaustive-deps.rule.ts) and then check the resulting node.type ===
AST_NODE_TYPES.ArrayExpression; add tests covering both "as const"
(TSAsExpression) and "satisfies" (TSSatisfiesExpression) forms to ensure these
assertion-wrapped array literals are recognized.
- Around line 75-76: The rule must stop relying on raw identifier text and
instead resolve symbols via import specifiers and scope bindings: update places
using isIdentifierWithOneOfNames, isIdentifierWithName, and the
queryClientVariables Set to resolve the node's binding (use
context.getScope()/sourceCode.getScope or eslint-utils findVariable) and then
verify the binding originates from a TanStack import via
helpers.isTanstackQueryImport by checking the ImportSpecifier/ImportDeclaration
and the imported.name (e.g., 'useQuery', 'useQueryClient', 'QueryClient'); when
tracking QueryClient results store the actual Variable/binding or the
ImportSpecifier reference instead of a string so membership checks are
scope-aware and won’t match shadowed parameters, and for aliased imports compare
the import specifier's imported.name to the canonical TanStack symbol names
rather than the local identifier text.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3697aff5-b7ea-4d4f-a1de-925c4b9f3ac8

📥 Commits

Reviewing files that changed from the base of the PR and between 7e5fe21 and 3a8e0f4.

📒 Files selected for processing (8)
  • .changeset/prefer-query-options-rule.md
  • docs/config.json
  • docs/eslint/eslint-plugin-query.md
  • docs/eslint/prefer-query-options.md
  • packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
  • packages/eslint-plugin-query/src/index.ts
  • packages/eslint-plugin-query/src/rules.ts
  • packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`:
- Around line 78-94: The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e887bb9-56cc-4d8e-be48-9e9b47c3ca38

📥 Commits

Reviewing files that changed from the base of the PR and between 3a8e0f4 and 26737a2.

📒 Files selected for processing (3)
  • docs/eslint/prefer-query-options.md
  • packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts
  • packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts
✅ Files skipped from review due to trivial changes (1)
  • docs/eslint/prefer-query-options.md

Comment on lines +78 to +94
function reportInlineQueryOptions(node: TSESTree.Node): void {
if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
context.report({
node,
messageId: 'preferQueryOptions',
})
}
}

function reportInlineFilterQueryKey(node: TSESTree.Node): void {
if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
context.report({
node,
messageId: 'preferQueryOptionsQueryKey',
})
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, locate and examine the target file
fd -t f "prefer-query-options.rule.ts" packages/eslint-plugin-query

Repository: TanStack/query

Length of output: 146


🏁 Script executed:

# Get the file size to determine how to read it
wc -l packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 150


🏁 Script executed:

# Read the entire file to understand the implementation
cat -n packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 12438


🏁 Script executed:

# Find test files for this rule
fd -t f "prefer-query-options" packages/eslint-plugin-query/src/rules --type f

Repository: TanStack/query

Length of output: 146


🏁 Script executed:

# Look for test directory
fd -t d "__tests__" packages/eslint-plugin-query/src/rules/prefer-query-options/

Repository: TanStack/query

Length of output: 40


🏁 Script executed:

# Find test files more broadly
fd "prefer-query-options" packages/eslint-plugin-query -type f | grep -i test

Repository: TanStack/query

Length of output: 228


🏁 Script executed:

# Look for test files in the rules directory
find packages/eslint-plugin-query -name "*prefer-query-options*" -type f

Repository: TanStack/query

Length of output: 218


🏁 Script executed:

# Read the test file
cat -n packages/eslint-plugin-query/src/__tests__/prefer-query-options.test.ts

Repository: TanStack/query

Length of output: 39919


🏁 Script executed:

# Double-check the exact line ranges mentioned in the review comment
# Lines 124-127 (queriesHooks handling)
sed -n '124,127p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 186


🏁 Script executed:

# Lines 210-288 (getReturnedObjectExpressions and getQueryObjects)
sed -n '210,288p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 2039


🏁 Script executed:

# Verify unwrapTypeAssertions implementation
sed -n '379,389p' packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts

Repository: TanStack/query

Length of output: 347


Unwrap asserted option objects before inspecting them.

unwrapTypeAssertions() only protects raw query-key arrays. Patterns like useQuery({ queryKey: ['todos'], queryFn: () => fetchTodos() } as const), queryClient.fetchQuery({ ... } satisfies SomeOptions), and useQueries({ queries: ([{ ... }] as const) }) bypass the rule because these paths still require a bare ObjectExpression/ArrayExpression. Add unwrapping before object checks and while traversing queries entries.

Suggested fix
     function reportInlineQueryOptions(node: TSESTree.Node): void {
-      if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
+      const expression = unwrapTypeAssertions(node)
+      if (
+        ASTUtils.isObjectExpression(expression) &&
+        hasInlineQueryOptions(expression)
+      ) {
         context.report({
           node,
           messageId: 'preferQueryOptions',
         })
       }
     }

     function reportInlineFilterQueryKey(node: TSESTree.Node): void {
-      if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
+      const expression = unwrapTypeAssertions(node)
+      if (
+        ASTUtils.isObjectExpression(expression) &&
+        hasInlineFilterQueryKey(expression)
+      ) {
         context.report({
           node,
           messageId: 'preferQueryOptionsQueryKey',
         })
       }
     }
@@
-          if (
-            queriesHooks.includes(importedName) &&
-            ASTUtils.isObjectExpression(options)
-          ) {
+          const expression = unwrapTypeAssertions(options)
+          if (
+            queriesHooks.includes(importedName) &&
+            ASTUtils.isObjectExpression(expression)
+          ) {
             const queries = ASTUtils.findPropertyWithIdentifierKey(
-              options.properties,
+              expression.properties,
               'queries',
             )?.value
@@
 function getReturnedObjectExpressions(
   node: TSESTree.Node,
 ): Array<TSESTree.ObjectExpression> {
+  node = unwrapTypeAssertions(node)
+
   if (ASTUtils.isObjectExpression(node)) {
     return [node]
   }
@@
 function getQueryObjects(
   node: TSESTree.Node,
 ): Array<TSESTree.ObjectExpression> {
+  node = unwrapTypeAssertions(node)
+
   if (node.type === AST_NODE_TYPES.ArrayExpression) {
-    return node.elements.flatMap((element) => {
-      if (element !== null && ASTUtils.isObjectExpression(element)) {
-        return [element]
-      }
-
-      return []
-    })
+    return node.elements.flatMap((element) =>
+      element === null ? [] : getReturnedObjectExpressions(element),
+    )
   }

Also applies to: 124-127, 210-288

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/eslint-plugin-query/src/rules/prefer-query-options/prefer-query-options.rule.ts`
around lines 78 - 94, The rule currently inspects nodes directly and misses
patterns wrapped in TypeScript assertions/satisfies; update
reportInlineQueryOptions and reportInlineFilterQueryKey to first call
unwrapTypeAssertions(node) and use the unwrapped node for
ASTUtils.isObjectExpression checks and subsequent
hasInlineQueryOptions/hasInlineFilterQueryKey evaluations, and likewise apply
unwrapTypeAssertions when traversing queries entries (the logic around the
queries array that checks each entry) so that asserted/satisfied
ObjectExpression/ArrayExpression forms are detected; keep existing messageIds
and only change the inspected node to the unwrapped result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation package: eslint-plugin-query

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant