createMemoryRouter
On this page

createMemoryRouter

Summary

Reference Documentation ↗

Create a new DataRouter that manages the application path using an in-memory History stack. Useful for non-browser environments without a DOM API.

Signature

function createMemoryRouter(
  routes: RouteObject[],
  opts?: MemoryRouterOpts,
): DataRouter

Params

routes

Application routes

opts.basename

Basename path for the application.

opts.dataStrategy

Override the default data strategy of loading in parallel. Only intended for advanced usage.

opts.future

Future flags to enable for the router.

opts.getContext

A function that returns an RouterContextProvider instance which is provided as the context argument to client actions, loaders and middleware. This function is called to generate a fresh context instance on each navigation or fetcher call.

opts.hydrationData

Hydration data to initialize the router with if you have already performed data loading on the server.

opts.initialEntries

Initial entries in the in-memory history stack

opts.initialIndex

Index of initialEntries the application should initialize to

opts.unstable_instrumentations

Array of instrumentation objects allowing you to instrument the router and individual routes prior to router initialization (and on any subsequently added routes via route.lazy or patchRoutesOnNavigation). This is mostly useful for observability such as wrapping navigations, fetches, as well as route loaders/actions/middlewares with logging and/or performance tracing.

let router = createBrowserRouter(routes, {
  unstable_instrumentations: [logging]
});


let logging = {
  router({ instrument }) {
    instrument({
      navigate: (impl, info) => logExecution(`navigate ${info.to}`, impl),
      fetch: (impl, info) => logExecution(`fetch ${info.to}`, impl)
    });
  },
  route({ instrument, id }) {
    instrument({
      middleware: (impl, info) => logExecution(
        `middleware ${info.request.url} (route ${id})`,
        impl
      ),
      loader: (impl, info) => logExecution(
        `loader ${info.request.url} (route ${id})`,
        impl
      ),
      action: (impl, info) => logExecution(
        `action ${info.request.url} (route ${id})`,
        impl
      ),
    })
  }
};

async function logExecution(label: string, impl: () => Promise<void>) {
  let start = performance.now();
  console.log(`start ${label}`);
  await impl();
  let duration = Math.round(performance.now() - start);
  console.log(`end ${label} (${duration}ms)`);
}

opts.patchRoutesOnNavigation

Lazily define portions of the route tree on navigations.

Returns

An initialized DataRouter to pass to <RouterProvider>

Docs and examples CC 4.0
Edit