0
Fork 0
mirror of https://github.com/TanStack/router.git synced 2026-11-16 19:38:07 +00:00
router/docs/guide/code-splitting.md
2023-12-25 16:20:18 -07:00

3.9 KiB

title
Code Splitting

Using lazyRouteComponent

Synchronous components are usually defined as functions and passed to the route.component option:

function MyComponent() {
  return <div>My Component</div>
}

const route = new Route({
  component: MyComponent,
})

But with TanStack Router, a route component can have a static preload method attached to it which will get called and awaited when the route is preloaded and/or loaded.

If we were to set this up manually (don't do this), it would look something like this:

const MyComponent = React.lazy(() => import('./MyComponent'))

MyComponent.preload = async () => {
  await import('./MyComponent')
}

const route = new Route({
  component: MyComponent,
})

This is a bit noisy and repetitive, so TanStack Router exports a lazyRouteComponent wrapper that you can use to simplify this process:

import { lazyRouteComponent } from '@tanstack/react-router'

const route = new Route({
  component: lazyRouteComponent(() => import('./MyComponent')),
})

The lazyRouteComponent wrapper not only implements React.lazy() under the hood, but automatically sets up the component with a preload method and promise management for you.

Handling Named exports with lazyRouteComponent

The lazyRouteComponent wrapper also allows you to easily load components that are named exports from a module. To use this functionality, provide the name of the exported component as a second argument to the function:

const route = new Route({
  component: lazyRouteComponent(() => import('./MyComponent'), 'NamedExport'),
})

lazyRouteComponent is also type safe, to ensure that you are only able to provide valid named exports from the module, which helps prevent runtime errors.

Data Loader Splitting

You may end up with a lot of data loaders that could potentially contribute to a large bundle size. If this is the case, you can code split your data loading logic using the Route's loader option. While this process makes it difficult to maintain type-safety with the parameters passed to your loader, you can always use the generic LoaderContext type to get most of the way there:

import { LoaderContext } from '@tanstack/react-router'

const route = new Route({
  path: '/my-route',
  component: MyComponent,
  loader: (...args) => import('./loader').then((d) => d.loader(...args)),
})

// In another file...
export const loader = async (context: LoaderContext) => {
  /// ...
}

Again, this process can feel heavy-handed, so TanStack Router exports another utility called lazyFn which is very similar to lazyRouteComponent that can help simplify this process:

import { lazyFn } from '@tanstack/react-router'

const route = new Route({
  path: '/my-route',
  component: MyComponent,
  loader: lazyFn(() => import('./loader'), 'loader'),
})

// In another file...a
export const loader = async (context: LoaderContext) => {
  /// ...
}

Accessing Route APIs in Code Split Files with the RouteApi class

As you might have guessed, importing the very route that is already importing the code-split file you're in is a circular dependency, both in types and at runtime. To avoid this, TanStack Router exports a handy RouteApi class that you can use to access a route's type-safe APIs:

import { Route } from '@tanstack/react-router'

const route = new Route({
  path: '/my-route',
  loader: () => ({
    foo: 'bar',
  }),
  component: lazyRouteComponent(() => import('./my-component'), 'MyComponent'),
})

// In my-component.tsx
import { RouteApi } from '@tanstack/react-router'

const routeApi = new RouteApi({ id: '/my-route' })

export function MyComponent() {
  const loaderData = routeApi.useLoaderData()
  //    ^? { foo: string }

  return <div>...</div>
}

The RouteApi class is also useful for accessing other type-safe APIs:

  • useLoaderData
  • useMatch
  • useParams
  • useRouteContext
  • useSearch