# Render Optimizations

TanStack Router includes several optimizations to ensure your components only re-render when necessary. These optimizations include:

## structural sharing

TanStack Router uses a technique called "structural sharing" to preserve as many references as possible between updates, which is particularly useful for state stored in the URL, such as search parameters.

For example, consider a `details` route with two search parameters, `foo` and `bar`, accessed like this:

```tsx
const search = Route.useSearch()
```

When only `bar` is changed by navigating from `/details?foo=f1&bar=b1` to `/details?foo=f1&bar=b2`, `search.foo` will be referentially stable and only `search.bar` will be replaced.

At the core level (`@tanstack/router-core`), structural sharing is applied automatically to location-derived fields and loader dependencies:

- `search` (`location.search` and `match.search`)
- `params` when staying on a matched route (`match.params`)
- `loaderDeps` (`match.loaderDeps`)
- `location.state`

Other match fields behave differently in `@tanstack/router-core`:

- `loaderData` keeps its reference across navigations that do not reload the route (for example, changing a search parameter that is not part of `loaderDeps`). When the loader runs again (for example after `router.invalidate()`, when `shouldReload` returns `true`, or when stale data reloads because the route is re-entered, its params or `loaderDeps` change, or the same URL is loaded again, whether blocking or in the background), `@tanstack/router-core` assigns the new loader result directly without running `replaceEqualDeep`.
- Route context (`beforeLoad` / `context`) is not structurally shared in `@tanstack/router-core` and is recreated on each navigation.

## fine-grained selectors

You can access and subscribe to the router state using various hooks like `useRouterState`, `useSearch`, and others. In React (`@tanstack/react-router`), selector hooks compare their returned value with referential equality (`===`). If you only want a specific component to re-render when a particular subset of the router state such as a subset of the search parameters changes, you can use partial subscriptions with the `select` property.

```tsx
// component won't re-render when `bar` changes
const foo = Route.useSearch({ select: ({ foo }) => foo })
```

### structural sharing with fine-grained selectors

The `select` function can perform various calculations on the router state, allowing you to return different types of values, such as objects. For example:

```tsx
const result = Route.useSearch({
  select: (search) => {
    return {
      foo: search.foo,
      hello: `hello ${search.foo}`,
    }
  },
})
```

Although this works, in React (`@tanstack/react-router`) it will cause your component to re-render each time, since `select` returns a new object on every run and referential equality (`===`) sees a different reference.

In React, you can avoid this re-rendering issue by enabling hook-level structural sharing. When enabled, the hook runs `replaceEqualDeep` between the previous and next returned values before comparing references with `===`, so deeply equal values reuse the previous reference. By default, hook-level structural sharing is turned off (`defaultStructuralSharing: false`) to maintain backward compatibility, though this may change in v2.

Hook-level structural sharing in React applies to the value returned by hooks that support the `structuralSharing` option (including `useLoaderData`, `useRouteContext`, `useSearch`, `useParams`, `useLoaderDeps`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`, `useLocation`, and `useRouterState`), both when `select` creates a derived object or array and when `select` is omitted. In particular, enabling `structuralSharing: true` on `useLoaderData` (with or without `select`) or setting `defaultStructuralSharing: true` on the router stabilizes JSON-compatible `loaderData` references across route reloads so deeply equal reload payloads do not cause unnecessary re-renders.

For `useRouteContext`, because `@tanstack/router-core` creates a new `match.context` object on each navigation, enabling `structuralSharing: true` (or `defaultStructuralSharing: true` on the router) can preserve the `match.context` reference across navigations when its properties remain equal (including unchanged references such as a `QueryClient`, which `replaceEqualDeep` compares with `===`). If a route context contains dynamic getters or non-JSON values that you do not want `replaceEqualDeep` to traverse, pass `structuralSharing: false` or select only the stable property you need (for example `select: (context) => context.queryClient`, with `structuralSharing: false` when `defaultStructuralSharing: true`).

In Solid (`@tanstack/solid-router`), match-based hooks (`useMatch`, `useSearch`, `useParams`, `useLoaderData`, `useLoaderDeps`, `useRouteContext`) and match list hooks (`useMatches`, `useParentMatches`, `useChildMatches`) always apply `replaceEqualDeep` inside `createMemo`, and `useLocation` and `useRouterState` apply it when `select` is provided. Solid does not use `defaultStructuralSharing` or a per-hook `structuralSharing` option.

To enable hook-level structural sharing in React, you have two options:

#### Enable it by default in the router options:

```tsx
const router = createRouter({
  routeTree,
  defaultStructuralSharing: true,
})
```

#### Enable it per hook usage as shown here:

```tsx
const result = Route.useSearch({
  select: (search) => {
    return {
      foo: search.foo,
      hello: `hello ${search.foo}`,
    }
  },
  structuralSharing: true,
})
```

For a route whose loader returns JSON-compatible data and reloads frequently, you can also enable it directly on `useLoaderData`:

```tsx
const data = Route.useLoaderData({
  structuralSharing: true,
})
```

> [!IMPORTANT]
> Structural sharing (`replaceEqualDeep`) only deep-compares plain objects and dense plain arrays. Non-plain values (such as class instances, `Date`, `Map`, `Set`, functions, and deferred promises) are compared only by reference (`===`) and are never deep-merged: an unchanged reference (like a `QueryClient` stored on router context) is preserved as-is, while newly created instances are not shared across updates. Plain objects with getters have those getters invoked during comparison (and flattened into plain data properties if a copy is created), and plain-object React elements or React Server Components can be traversed, so pass `structuralSharing: false` for hooks returning those.

In line with TanStack Router's type-safe design, TypeScript raises an error if a `select` callback returns functions or objects containing methods (such as `Date`, `Map`, `Set`, or class instances with methods) while structural sharing is enabled:

```tsx
const result = Route.useSearch({
  select: (search) => {
    return {
      date: new Date(),
    }
  },
  structuralSharing: true,
})
```

This compile-time check does not reject every non-JSON type (for example, `bigint`, `symbol`, or class instances without methods) and does not run when `select` is omitted (such as `Route.useLoaderData({ structuralSharing: true })`, `Route.useRouteContext()`, or other unselected hooks with `defaultStructuralSharing: true`). If `defaultStructuralSharing: true` is enabled in the router options, set `structuralSharing: false` when opting out of `replaceEqualDeep` (for example, for plain objects with getters, React elements / React Server Components, values that cannot benefit from deep comparison, or `select` callbacks that return functions or objects with methods).
