new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React Router · API · all subjects

components

114 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

React Router Components documentation index

The Components section is the first main topic in the React Router API documentation, providing a catalog of React Router components.

StaticRouterProvider server rendering example

Example of using StaticRouterProvider for server-side rendering: First create a static handler and query the request to get context. If context is not a Response, create a static router with the data routes and context, then render StaticRouterProvider with the router and context to a string using ReactDOMServer.renderToString, and return it with Content-Type text/html header.

StaticRouterProvider purpose and mode

StaticRouterProvider is a DataRouter for server-side rendering that does not navigate to any other Location. It is used in data router mode to render routes on the server where there is no stateful UI.

StaticRouterProvider nonce prop

The nonce prop is a string used for the nonce attribute on the hydration script tag. This follows the standard HTML nonce global attribute for content security policy.

StaticRouterProvider hydrate prop

The hydrate prop is a boolean that controls whether to hydrate the router on the client. It defaults to true.

StaticRouterProvider component signature

StaticRouterProvider is a function component that accepts an object with properties: context (StaticHandlerContext), router (DataRouter), hydrate (boolean, default true), and nonce (string for script tag nonce attribute).

StaticRouterProvider context prop

The context prop is a StaticHandlerContext object returned from StaticHandler's query method. This is required.

StaticRouterProvider router prop

The router prop is a static DataRouter instance created by createStaticRouter function. This is required.

RouterProvider flushSync prop

The flushSync prop accepts a ReactDOM.flushSync implementation for flushing updates. This prop is usually not needed because RouterProvider exported from 'react-router/dom' handles this internally. If rendering in a non-DOM environment, import RouterProvider from 'react-router' and ignore this prop.

RouterProvider onError prop

The onError prop is an optional error handler function called for any middleware, loader, action, or render errors encountered in the application. It receives error and info parameters. The info parameter contains location, params, pattern, and errorInfo (from componentDidCatch, only for render errors). This is useful for logging or reporting errors instead of in an ErrorBoundary because it runs once per error without re-rendering.

RouterProvider useTransitions prop behavior when undefined

When useTransitions is left undefined, all state updates are wrapped in React.startTransition. This can lead to buggy behaviors if you are wrapping your own navigations or fetchers in startTransition.

RouterProvider useTransitions prop behavior when true

When useTransitions is set to true, Link and Form navigations will be wrapped in React.startTransition and router state changes will be wrapped in React.startTransition and also sent through useOptimistic to surface mid-navigation router state changes to the UI.

RouterProvider useTransitions prop behavior when false

When useTransitions is set to false, the router will not leverage React.startTransition or React.useOptimistic on any navigations or state changes.

RouterProvider example usage

import { createBrowserRouter } from "react-router"; import { RouterProvider } from "react-router/dom"; import { createRoot } from "react-dom/client"; const router = createBrowserRouter(routes); createRoot(document.getElementById("root")).render( <RouterProvider router={router} /> );

RouterProvider export locations

RouterProvider is exported both from 'react-router' and 'react-router/dom'. The only difference is that 'react-router/dom' automatically wires up React DOM's flushSync implementation. You almost always want to use the version from 'react-router/dom' unless you're running in a non-DOM environment.

RouterProvider onError example

<RouterProvider onError={(error, info) => { let { location, params, pattern, errorInfo } = info; console.error(error, location, errorInfo); reportToErrorService(error, location, errorInfo); }} />

RouterProvider component overview

RouterProvider is a React component that renders the UI for a given DataRouter. It should typically be placed at the top of an app's element tree. The router prop should be a single router instance created outside of the React tree. Avoid creating new routers during React renders/re-renders.

RouterProvider props signature

RouterProvider accepts the following props: router (required, DataRouter instance), flushSync (optional, ReactDOM.flushSync implementation), onError (optional, error handler function), and useTransitions (optional, boolean or undefined to control React.startTransition wrapping).

RouterProvider router prop

The router prop is a required DataRouter instance used for navigation and data fetching. It must be created outside of the React tree before being passed to RouterProvider. Creating new routers during React renders or re-renders should be avoided.

createStaticHandler routes parameter

The routes parameter accepts an array of RouteObject items that define the routes to create a static handler for.

createStaticHandler function signature

createStaticHandler takes a RouteObject array as the first parameter and an optional CreateStaticHandlerOptions object as the second parameter. It returns a StaticHandler object that can be used to query data for the provided routes.

createStaticHandler opts.basename option

The opts.basename parameter sets the base URL for the static handler. Its default value is '/'.

createStaticHandler opts.future option

The opts.future parameter provides future flags for the static handler.

createStaticHandler server-side data loading example

The following example shows how to use createStaticHandler to perform server-side data loading: export async function handleRequest(request: Request) { let { query, dataRoutes } = createStaticHandler(routes); let context = await query(request); if (context instanceof Response) { return context; } let router = createStaticRouter(dataRoutes, context); return new Response( ReactDOMServer.renderToString(<StaticRouterProvider ... />), { headers: { "Content-Type": "text/html" } } ); }

createStaticHandler return value structure

createStaticHandler returns a StaticHandler object that contains at least a query method and a dataRoutes property. The query method is an async function that accepts a Request object and returns either a context object or a Response.

createStaticRouter usage example

Example showing how to use createStaticRouter for server-side rendering: first call createStaticHandler to get query and dataRoutes, then call query(request), and if the result is not a Response, pass dataRoutes and context to createStaticRouter. The router is then used with StaticRouterProvider to render with ReactDOMServer.renderToString.

createStaticRouter function signature

createStaticRouter is a function that creates a static DataRouter for server-side rendering. It takes three parameters: routes (array of RouteObject), context (StaticHandlerContext), and opts (optional object with branches and future properties). It returns a DataRouter.

createStaticRouter context parameter

The context parameter is a StaticHandlerContext. This is the context returned from a StaticHandler's query method.

createStaticRouter opts.future parameter

The opts.future parameter is a Partial<FutureConfig> object. It contains future flags for the static DataRouter.

createMemoryRouter opts.getContext

The opts.getContext option is a function that returns a 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.

createMemoryRouter opts.initialIndex

The opts.initialIndex option specifies the index of initialEntries the application should initialize to.

createMemoryRouter opts.instrumentations

The opts.instrumentations option is an 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, and middlewares with logging and/or performance tracing. Each instrumentation object can have a router method and a route method, where router receives an instrument function to wrap navigate and fetch operations, and route receives an instrument function to wrap middleware, loader, and action operations.

createMemoryRouter opts.patchRoutesOnNavigation

The opts.patchRoutesOnNavigation option allows you to lazily define portions of the route tree on navigations.

createMemoryRouter dataStrategy example

Example of using dataStrategy with createMemoryRouter: let router = createBrowserRouter(routes, { async dataStrategy({ matches, request, runClientMiddleware, }) { const matchesToLoad = matches.filter((m) => m.shouldCallHandler(), ); const results: Record<string, DataStrategyResult> = {}; await runClientMiddleware(() => Promise.all( matchesToLoad.map(async (match) => { results[match.route.id] = await match.resolve(); }), ), ); return results; }, });

createMemoryRouter instrumentations example

Example of using instrumentations with createMemoryRouter: let router = createBrowserRouter(routes, { 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)`); }

createMemoryRouter purpose

createMemoryRouter creates a new DataRouter that manages the application path using an in-memory History stack. It is useful for non-browser environments without a DOM API.

createMemoryRouter opts.basename

The opts.basename option specifies the basename path for the application.

createMemoryRouter opts.dataStrategy

The opts.dataStrategy option allows you to override the default data strategy of running loaders in parallel. It receives an object with matches, request, and runClientMiddleware properties. The dataStrategy function should return a Record<string, DataStrategyResult> containing the results keyed by match.route.id.

createMemoryRouter opts.future

The opts.future option allows you to specify future flags to enable for the router.

createMemoryRouter opts.hydrationData

The opts.hydrationData option provides hydration data to initialize the router with if you have already performed data loading on the server.

createMemoryRouter opts.initialEntries

The opts.initialEntries option specifies the initial entries in the in-memory history stack.

createMemoryRouter function signature

createMemoryRouter is a function that takes routes (RouteObject[]) and optional opts (MemoryRouterOpts) as parameters and returns a DataRouter. The signature is: function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): DataRouter

createMemoryRouter should not be in React state

Data Routers from createMemoryRouter should not be held in React state. You should create your router once outside of the React tree and pass it to RouterProvider.

BrowserRouter children prop

The children prop of BrowserRouter accepts Route components that describe your route configuration.

BrowserRouter component signature

BrowserRouter is a function component that accepts BrowserRouterProps and returns a declarative Router using the browser History API for client-side routing.

BrowserRouter props interface

BrowserRouter accepts four props: basename (string, application basename), children (Route components describing route configuration), useTransitions (boolean or undefined, controls whether router state updates are wrapped in React.startTransition), and window (Window object override, defaults to global window instance).

BrowserRouter basename prop

The basename prop sets the application basename for BrowserRouter.

BrowserRouter window prop

The window prop of BrowserRouter accepts a Window object override. It defaults to the global window instance.

HashRouter window prop default

The window prop of HashRouter defaults to the global window instance when not specified.

HashRouter component signature

HashRouter is a declarative router component that stores the location in the hash portion of the URL so it is not sent to the server. The signature is: function HashRouter({ basename, children, useTransitions, window }: HashRouterProps)

HashRouter props

HashRouter accepts four props: basename (application basename), children (Route components describing your route configuration), useTransitions (control whether router state updates are internally wrapped in React.startTransition), and window (Window object override, defaults to the global window instance).

unstable_HistoryRouter basename prop

The basename prop on unstable_HistoryRouter sets the application basename.

unstable_HistoryRouter component signature

unstable_HistoryRouter is a declarative Router component that accepts a pre-instantiated history object. The function signature is: function HistoryRouter({ basename, children, history, useTransitions }: HistoryRouterProps)

unstable_HistoryRouter children prop

The children prop on unstable_HistoryRouter accepts Route components describing the route configuration.

unstable_HistoryRouter history prop

The history prop on unstable_HistoryRouter accepts a History implementation for use by the router.

unstable_HistoryRouter useTransitions prop

The useTransitions prop on unstable_HistoryRouter controls whether router state updates are internally wrapped in React.startTransition. When left undefined, all router state updates are wrapped in React.startTransition. When set to true, Link and Form navigations will be wrapped in React.startTransition and all router state updates are wrapped in React.startTransition. When set to false, the router will not leverage React.startTransition on any navigations or state changes.

unstable_HistoryRouter discouraged usage

Using your own history object with unstable_HistoryRouter is highly discouraged and may add two versions of the history library to your bundles unless you use the same version of the history library that React Router uses internally.

unstable_HistoryRouter is experimental API

unstable_HistoryRouter is an experimental API that is subject to breaking changes in minor and patch releases.

MemoryRouter initialEntries prop

The initialEntries prop on MemoryRouter specifies the initial entries in the in-memory history stack.

MemoryRouter children prop

The children prop on MemoryRouter accepts nested Route elements describing the route tree.

Give your agent this brain