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 2 of 2.

MemoryRouter initialIndex prop

The initialIndex prop on MemoryRouter specifies the index of initialEntries the application should initialize to.

MemoryRouter useTransitions prop

The useTransitions prop on MemoryRouter 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.

MemoryRouter purpose

MemoryRouter is a declarative Router component that stores all entries in memory.

MemoryRouter basename prop

The basename prop on MemoryRouter specifies the application basename.

MemoryRouter component signature

MemoryRouter is a function component that accepts MemoryRouterProps and returns React.ReactElement. The signature is: function MemoryRouter({ basename, children, initialEntries, initialIndex, useTransitions }: MemoryRouterProps): React.ReactElement

StaticRouter basename prop

The basename prop sets the base URL for the static router. Its default value is '/'.

StaticRouter children prop

The children prop specifies the child elements to render inside the static router.

StaticRouter location prop

The location prop specifies the Location to render the static router at. Its default value is '/'.

StaticRouter component signature

StaticRouter is a component that accepts an object with three properties: basename (the base URL for the static router, default '/'), children (the child elements to render), and location (the Location to render at, default '/'). It is called as: function StaticRouter({ basename, children, location: locationProp = "/" }: StaticRouterProps)

StaticRouter purpose

StaticRouter is a Router component that may not navigate to any other Location. It is useful on the server where there is no stateful UI.

Router direct rendering not recommended

You usually won't render a Router component directly. Instead, you should render a router that is more specific to your environment such as BrowserRouter in web browsers or ServerRouter for server rendering.

Router component signature

The Router component accepts the following parameters: basename with default "/", children defaulting to null, location as locationProp, navigationType defaulting to NavigationType.Pop, navigator, static as staticProp defaulting to false, and useTransitions. It returns React.ReactElement or null.

Router basename prop

The basename prop sets the base path for the application. This base path is prepended to all locations.

Router children prop

The children prop accepts nested Route elements describing the route tree. Default is null.

Router location prop

The location prop specifies the location to match against. It defaults to the current location. The value can be either a string or a Location object.

Router navigationType prop

The navigationType prop specifies the type of navigation that triggered the location change. It defaults to NavigationType.Pop.

Router navigator prop

The navigator prop specifies the navigator to use for navigation. This is usually a history object or a custom navigator that implements the Navigator interface.

Router static prop

The static prop indicates whether the router is static or not, used for server-side rendering. When set to true, the router will not be reactive to location changes. Default is false.

Router useTransitions prop behavior

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

Router purpose

The Router component provides location context for the rest of the application.

HydratedRouter function signature and location

HydratedRouter is a framework-mode router component function with signature `function HydratedRouter(props: HydratedRouterProps)`. It is located in packages/react-router/lib/dom-export/hydrated-router.tsx.

HydratedRouter purpose and usage

HydratedRouter is a framework-mode router component used to hydrate a router from a ServerRouter. It is used in entry.client.tsx following server-side rendering.

HydratedRouter getContext prop

The getContext prop accepts a context factory function to be passed through to createBrowserRouter. This function is called to create a fresh context instance on each navigation or fetch, and the context is made available to clientAction and clientLoader functions.

HydratedRouter onError prop

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

HydratedRouter onError example usage

Example of HydratedRouter with onError handler: ```tsx <HydratedRouter onError={(error, info) => { let { location, params, pattern, errorInfo } = info; console.error(error, location, errorInfo); reportToErrorService(error, location, errorInfo); }} /> ``` This example shows destructuring the info object to access location, params, pattern, and errorInfo, and then logging and reporting the error.

ServerRouter context prop

The context prop for ServerRouter is the entry context containing the manifest, route modules, and other data needed for rendering.

ServerRouter component signature

ServerRouter is a function component for server-side rendering in React Router Framework Mode. It accepts ServerRouterProps and returns a ReactElement. The function signature is: function ServerRouter({ context, url, nonce }: ServerRouterProps): ReactElement

ServerRouter url prop

The url prop for ServerRouter is the URL of the request being handled.

ServerRouter nonce prop

ServerRouter accepts an optional nonce prop for Content Security Policy (CSP) compliance. This nonce is applied to inline scripts rendered by React Router and used as the default for nonce-aware components such as <Links>, <Scripts>, and <ScrollRestoration> when they do not provide their own nonce.

@react-router/architect createRequestHandler example

Example of using @react-router/architect: import { createRequestHandler } from '@react-router/architect'; import * as build from './build/server'; export const handler = createRequestHandler({ build, });

@react-router/node package

@react-router/node is not a direct adapter like the others but contains utilities for working with Node-based adapters.

@react-router/cloudflare createRequestHandler example

Example of using @react-router/cloudflare: import { RouterContextProvider, createContext, createRequestHandler, } from 'react-router'; const cloudflareContext = createContext<{ env: Env; ctx: ExecutionContext; }>(); const requestHandler = createRequestHandler( () => import('virtual:react-router/server-build'), import.meta.env.MODE, ); export default { async fetch(request, env, ctx) { let routerContext = new RouterContextProvider(); routerContext.set(cloudflareContext, { env, ctx }); return requestHandler(request, routerContext); }, } satisfies ExportedHandler<Env>;

@react-router/express createRequestHandler example

Example of using @react-router/express with Express: const { createRequestHandler } = require('@react-router/express'); const express = require('express'); const app = express(); app.all( '*', createRequestHandler({ build: require('./build'), getLoadContext(req, res) { return {}; }, }), );

createRequestHandler Express options

The createRequestHandler in @react-router/express accepts an options object with: build (required) - the build output files from 'react-router build' and 'react-router dev'; getLoadContext(req, res) (optional) - a function that returns an object to be available as `context` in loaders and actions, allowing bridging between the server and React Router.

unstable_RSCHydratedRouter signature and props

The unstable_RSCHydratedRouter is a component function with signature: function RSCHydratedRouter({ createFromReadableStream, fetch: fetchImplementation = fetch, payload, getContext }: RSCHydratedRouterProps). It hydrates a server rendered unstable_RSCPayload in the browser. The createFromReadableStream prop is your react-server-dom-xyz/client's createFromReadableStream function, used to decode payloads from the server and is required. The fetch prop is an optional fetch implementation that defaults to global fetch. The payload prop is the decoded unstable_RSCPayload to hydrate and is required. The getContext prop is an optional function that returns a RouterContextProvider instance which is provided as the context argument to client actions, loaders and middleware, and is called to generate a fresh context instance on each navigation or fetcher call.

RSCStaticRouter props

RSCStaticRouter accepts props with the following fields: getPayload (required) - a function that starts decoding of the unstable_RSCPayload, usually passed through from unstable_routeRSCServerRequest's renderHTML. nonce (optional) - a nonce string used as the default for nonce-aware components such as Links and ScrollRestoration.

unstable_RSCStaticRouter component

unstable_RSCStaticRouter is an experimental React Router component that pre-renders an unstable_RSCPayload to HTML. It is typically used in unstable_routeRSCServerRequest's renderHTML callback. This API is experimental and subject to breaking changes in minor/patch releases.

RSCStaticRouter signature

The function signature is: function RSCStaticRouter({ getPayload, nonce }: RSCStaticRouterProps)

RouterContextProvider type-safe context example

Example showing type-safe context usage with RouterContextProvider: create a context with a specific type (e.g., User | null), instantiate RouterContextProvider, use set() to store a value, and use get() to retrieve it with the type automatically inferred.

RouterContextProvider constructor and set method

RouterContextProvider is a class used to write and read values in application context in a type-safe way. The set() method takes a React context and a value to store, and the value type is enforced to match the context type.

RouterContextProvider get method

RouterContextProvider has a get() method that retrieves values from a React context. The return type is automatically inferred from the context type, providing type-safe retrieval.

RouterContextProvider usage with middleware

RouterContextProvider is primarily intended for usage with middleware in React Router applications.

HydrateFallback export in route modules

On initial page load, the route component renders only after the client loader is finished. If exported, a HydrateFallback can render immediately in place of the route component, providing a loading state during hydration.

Route module default export

The default export in a route module defines the component that will render when the route matches. This is the component that React Router will render for that route.

ErrorBoundary export in route modules

When other route module APIs throw, the route module ErrorBoundary will render instead of the route component. It receives the error via useRouteError hook and can check if it is a RouteErrorResponse using isRouteErrorResponse utility.

ErrorBoundary example

Example showing ErrorBoundary that uses useRouteError hook and isRouteErrorResponse utility to distinguish between RouteErrorResponse errors and regular Error instances, rendering appropriate error UI for each.

HydrateFallback example

Example showing route with clientLoader, HydrateFallback that displays 'Loading Game...', and default component that renders after client loader completes with the data.

HydrateFallback component

HydrateFallback is a component exported from a route that is rendered while the clientLoader is running during initial hydration. It is used to show a loading UI to the user while data is being fetched.

Component receiving loader data

Example: export default function Product({ loaderData }: Route.ComponentProps) { const { name, description } = loaderData; return ( <div> <h1>{name}</h1> <p>{description}</p> </div> ); }

React state for sidebar visibility example

Simple temporary sidebar visibility state can be managed with React state using useState: `const [isOpen, setIsOpen] = useState(false);` This approach is simple and encapsulated but transient—it doesn't survive page refreshes or component unmounts.

Local storage implementation with effects

To use local storage with React state, initialize state in useLayoutEffect to avoid server rendering errors, then synchronize changes in useEffect: Initialize with `useLayoutEffect(() => { const isOpen = window.localStorage.getItem('sidebar'); setIsOpen(isOpen); }, []);` and sync with `useEffect(() => { window.localStorage.setItem('sidebar', isOpen); }, [isOpen]);`

RSCHydratedRouter component for client hydration

The `RSCHydratedRouter` component from react-router/dom is used in entry.browser.tsx to hydrate the generated HTML. It accepts createFromReadableStream and payload props, and supports formState option.

RSCStaticRouter component for HTML rendering

The `RSCStaticRouter` component from react-router is used in entry.ssr.tsx to render the router to HTML. It accepts a `getPayload` function and optional `nonce` prop for CSP support.

React Router components becoming redundant in Remix

Some aspects of @remix-run/react's components.tsx file become fully redundant after the migration and can be removed in favor of re-exporting from react-router-dom: Form, useFormAction, useSubmit, useMatches, and useFetchers.

Give your agent this brain