# Prefer structuralSharing on React TanStack Router hooks with select

In `@tanstack/react-router`, hooks that accept a `select` function compare the previous and next selected values by reference equality by default. When `select` returns a new object or array literal (for example `select: (s) => ({ page: s.page, tab: s.tab })` or `select: (matches) => matches.map((m) => m.routeId)`), React sees a new reference on every router state update and re-renders the component even when all nested values are unchanged.

Enabling `structuralSharing: true` on the hook call (or setting `defaultStructuralSharing: true` globally in `createRouter`) compares JSON-compatible objects and arrays deeply and preserves previous references when their contents are equal.

This type-aware rule applies only to `@tanstack/react-router` hooks that support `structuralSharing`:

- `useRouterState`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`
- `useLoaderData`, `useLoaderDeps`, `useParams`, `useSearch`, `useLocation`, `useRouteContext`
- Route-bound variants on `Route`, `RootRoute`, `LazyRoute`, and `getRouteApi(...)`: `useMatch`, `useLoaderData`, `useLoaderDeps`, `useParams`, `useSearch`, `useRouteContext`

The rule inspects TypeScript type information at each callsite and only reports when **all** of the following hold:

1. The relevant router types are **not** provably configured with `defaultStructuralSharing: true`. For `useRouterState`, a provided non-nullish `opts.router` override is checked, while an omitted, `undefined`, or `null` `opts.router` falls back to the context router registered via `interface Register` (an optional or nullable `opts.router` requires both the override and the context router to enable it); for all other hooks, the registered context router is checked. Calls are skipped only when every applicable router type provably sets `defaultStructuralSharing: true`, so packages where `interface Register` is not augmented, `any`-typed router overrides, or unions containing both enabled and disabled routers can still be reported.
2. `structuralSharing` is not already specified (`structuralSharing: true` satisfies the rule and `structuralSharing: false` is respected as an explicit opt-out).
3. `select` is provided and returns a JSON-compatible value containing at least one structurally shareable object, array, or tuple that `@tanstack/react-router`'s own types allow with `structuralSharing: true`.

The rule intentionally ignores:

- Hooks called without `select` (unselected state/match hooks are covered by [`@tanstack/router/no-unselected-router-state`](./no-unselected-router-state.md); `useSearch`, `useParams`, `useLoaderDeps`, and `useLocation` already preserve or structurally share their core fields internally, `useLoaderData` keeps its reference across non-reloading navigations (reloads assign `match.loaderData` directly without `replaceEqualDeep`), route contexts frequently hold non-JSON values, and `StructuralSharingOption` bypasses `ValidateJSON` whenever `select` is omitted)
- Primitive-only selectors (`string`, `number`, `boolean`, `null`, `undefined`, etc.), where reference equality already prevents redundant re-renders
- Non-JSON-compatible return types (`Date`, `Map`, `Set`, `RegExp`, `Error`, `Promise`, functions, class instances, React elements, `any`, `unknown`)

This rule requires type-aware linting (`parserOptions.projectService: true`) and is included in the `flat/react-recommended-type-checked` and `react-recommended-type-checked` configs. Files without TypeScript type information (for example JavaScript files or files covered by `disableTypeChecked`) are skipped automatically.

See the [Render Optimizations guide](../guide/render-optimizations.md) for more information.

## Rule Details

Examples of **incorrect** code for this rule (when `defaultStructuralSharing` is not `true` on the router):

<!-- ::start:tabs variant="files" -->

```tsx title="src/components/PostFilters.tsx"
/* eslint "@tanstack/router/prefer-structural-sharing": "warn" */
import { useMatches, useSearch } from '@tanstack/react-router'

export function PostFilters() {
  const filters = useSearch({
    from: '/posts',
    select: (search) => ({
      page: search.page,
      tag: search.tag,
    }),
  })

  const routeIds = useMatches({
    select: (matches) => matches.map((match) => match.routeId),
  })

  return (
    <div>
      {filters.page} - {routeIds.join('/')}
    </div>
  )
}
```

<!-- ::end:tabs -->

Examples of **correct** code for this rule:

<!-- ::start:tabs variant="files" -->

```tsx title="src/components/PostFilters.tsx"
/* eslint "@tanstack/router/prefer-structural-sharing": "warn" */
import { useLoaderData, useMatches, useSearch } from '@tanstack/react-router'

export function PostFilters() {
  // Enable structuralSharing on the hook call
  const filters = useSearch({
    from: '/posts',
    select: (search) => ({
      page: search.page,
      tag: search.tag,
    }),
    structuralSharing: true,
  })

  // Explicit opt-out is respected
  const routeIds = useMatches({
    select: (matches) => matches.map((match) => match.routeId),
    structuralSharing: false,
  })

  // Primitive selectors already compare equal by reference
  const page = useSearch({
    from: '/posts',
    select: (search) => search.page,
  })

  // Non-JSON values (such as Date or functions) are not flagged
  const createdAt = useLoaderData({
    from: '/posts',
    select: (data) => data.createdAt,
  })

  return (
    <div>
      {page} - {filters.tag} - {routeIds.length} - {createdAt.toISOString()}
    </div>
  )
}
```

```tsx title="src/router.tsx"
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

// Or enable defaultStructuralSharing globally on your registered router:
export const router = createRouter({
  routeTree,
  defaultStructuralSharing: true,
})

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router
  }
}
```

<!-- ::end:tabs -->

## Attributes

- [x] ✅ React Recommended Type-Checked (`flat/react-recommended-type-checked`, `react-recommended-type-checked`)
- [x] 💡 Has suggestions
- [x] 💭 Requires type information
