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

hooks

187 notes in this subject, read out of this brain and free to use. This is page 3 of 4.

unstable_useRouterState replaces multiple hooks

unstable_useRouterState consolidates the information previously obtained from useLocation, useSearchParams, useParams, useMatches, useNavigation, and useNavigationType into a single hook.

unstable_useRouterState hook summary

unstable_useRouterState is an experimental hook that consolidates router state information. It returns an object with active and pending properties. This API is subject to breaking changes in minor/patch releases and should be used with caution. The hook is available in framework and data modes.

unstable_useRouterState active state

The active property of unstable_useRouterState contains the current location state. It includes: active.location (replaces useLocation()), active.searchParams (replaces useSearchParams()[0]), active.params (replaces useParams()), active.matches (replaces useMatches()), and active.type (replaces useNavigationType()).

unstable_useRouterState pending state

The pending property of unstable_useRouterState is only populated during a navigation. It includes: pending.location (replaces useNavigation().location), pending.searchParams (equivalent to new URLSearchParams(useNavigation().search)), pending.params (not directly accessible with other hooks), pending.matches (not directly accessible with other hooks), pending.type (not directly accessible with other hooks), pending.state (replaces useNavigation().state), pending.formMethod (replaces useNavigation().formMethod), pending.formAction (replaces useNavigation().formAction), pending.formEncType (replaces useNavigation().formEncType), pending.formData (replaces useNavigation().formData), pending.json (replaces useNavigation().json), and pending.text (replaces useNavigation().text).

unstable_useRouterState return type

unstable_useRouterState returns a value of type unstable_RouterState.

useRoutes hook overview

useRoutes is the hook version of the Routes component. It accepts route configuration objects with the same properties as Routes component props instead of using JSX components. This allows for programmatic route definition.

useRoutes example with nested routes

Example: function App() { let element = useRoutes([ { path: "/", element: <Dashboard />, children: [ { path: "messages", element: <DashboardMessages /> }, { path: "tasks", element: <DashboardTasks /> } ] }, { path: "team", element: <AboutPage /> } ]); return element; }

useRoutes hook signature

useRoutes is a hook that takes an array of RouteObject and an optional location argument, and returns either a React element or null. The signature is: function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null

useRoutes routes parameter

The routes parameter is an array of RouteObject elements that define the route hierarchy. This is a required parameter.

useRoutes locationArg parameter

The locationArg parameter is optional and accepts either a Partial<Location> object or a pathname string. It allows you to use a custom location instead of the current location.

useRoutes return value

useRoutes returns a React element representing the matched route, or null if no routes matched.

useSubmit hook returns SubmitFunction

useSubmit is a hook that returns a SubmitFunction. It has no parameters. The function signature is: function useSubmit(): SubmitFunction.

useSubmit example with onChange handler

This example shows useSubmit being used to submit a form when it changes: import { useSubmit } from "react-router"; function SomeComponent() { const submit = useSubmit(); return (<Form onChange={(event) => submit(event.currentTarget)} />); }

useSubmit provides imperative form submission

useSubmit gives you a function to submit a form imperatively from code instead of requiring a user interaction. This is an alternative to using the <Form> component declaratively.

useSearchParams with useEffect example

useEffect(() => { console.log(searchParams.get('tab')); }, [searchParams]);

useSearchParams hook basic usage

useSearchParams returns a tuple of the current URL's URLSearchParams and a function to update them. Setting the search params causes a navigation. It is imported from 'react-router'.

useSearchParams signature

The function signature is: function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams]

useSearchParams defaultInit parameter

The defaultInit parameter initializes the search params with a default value, but it will not change the URL on the first render. It accepts a search param string, an object with keys mapping to values (where values can be arrays for multiple values), an array of tuples, or a URLSearchParams object.

setSearchParams function formats

setSearchParams accepts multiple formats: a search param string like '?tab=1', an object like { tab: '1' }, an object with array values for multiple values like { brand: ['nike', 'reebok'] }, an array of tuples like [['tab', '1']], or a URLSearchParams object.

setSearchParams function callback

setSearchParams supports a function callback that receives the current searchParams and returns the modified searchParams, similar to React's setState. However, the function callback version does not support the queueing logic that React's setState implements—multiple calls to setSearchParams in the same tick will not build on the prior value.

setSearchParams function callback example

setSearchParams((searchParams) => { searchParams.set('tab', '2'); return searchParams; });

useSearchParams basic example

import { useSearchParams } from 'react-router'; export function SomeComponent() { const [searchParams, setSearchParams] = useSearchParams(); // ... }

searchParams is a stable reference

The searchParams object is a stable reference, so it can be reliably used as a dependency in React's useEffect hooks without causing unnecessary re-renders.

searchParams is mutable but should not be mutated directly

The searchParams object is mutable. If you change the object without calling setSearchParams, its values will change between renders if some other state causes the component to re-render and the URL will not reflect the values. Always use setSearchParams to update search params.

useViewTransitionState return value

useViewTransitionState returns true if there is an active View Transition API transition and the resolved path matches either the transition's destination pathname or source pathname. Otherwise it returns false.

useViewTransitionState purpose

useViewTransitionState is used to detect when there is an active View Transition and the specified location matches either the URL being navigated to or the URL being navigated from. This enables applying finer-grained styles to elements to customize the view transition. View transitions must be enabled for the navigation via LinkProps.viewTransition, or via the Form, submit, or navigate call.

useViewTransitionState hook signature

useViewTransitionState is a hook that takes a To location and an optional options object with a relative property. The signature is: function useViewTransitionState(to: To, { relative }?: { relative?: RelativeRoutingType } = {}). The hook is available in framework and data modes.

useViewTransitionState to parameter

The to parameter accepts a To location to compare against the active transition's current and next URLs.

useViewTransitionState options.relative parameter

The options.relative parameter specifies the relative routing type to use when resolving the to location. It defaults to 'route' and accepts a RelativeRoutingType value.

unstable_createCallServer function signature

unstable_createCallServer is a function that creates a React callServer implementation for React Router. It accepts an options object with properties: createFromReadableStream (BrowserCreateFromReadableStreamFunction, required), createTemporaryReferenceSet (function that returns unknown, required), encodeReply (EncodeReplyFunction, required), and fetch (optional function taking a Request and returning Promise<Response>, defaults to global fetch). It returns a function that can be used to call server actions.

unstable_createCallServer example setup

Example of setting up unstable_createCallServer with React Router: import { createFromReadableStream, createTemporaryReferenceSet, encodeReply, setServerCallback } from "@vitejs/plugin-rsc/browser"; import { unstable_createCallServer as createCallServer } from "react-router"; setServerCallback(createCallServer({ createFromReadableStream, createTemporaryReferenceSet, encodeReply }));

createCallServer createFromReadableStream parameter

The createFromReadableStream parameter of unstable_createCallServer should be your react-server-dom-xyz/client's createFromReadableStream function. It is used to decode payloads from the server.

createCallServer createTemporaryReferenceSet parameter

The createTemporaryReferenceSet parameter of unstable_createCallServer is a function that creates a temporary reference set for the RSC (React Server Components) payload.

createCallServer encodeReply parameter

The encodeReply parameter of unstable_createCallServer should be your react-server-dom-xyz/client's encodeReply function. It is used when sending payloads to the server.

createCallServer fetch parameter

The fetch parameter of unstable_createCallServer is optional and defaults to the global fetch implementation. When provided, it should be a function that accepts a Request and returns a Promise<Response>.

unstable_getRSCStream example with RSC hydration

Example usage: import { startTransition, StrictMode } from "react"; import { hydrateRoot } from "react-dom/client"; import { unstable_getRSCStream as getRSCStream, unstable_RSCHydratedRouter as RSCHydratedRouter } from "react-router"; import type { unstable_RSCPayload as RSCPayload } from "react-router"; createFromReadableStream(getRSCStream()).then((payload: RSCServerPayload) => { startTransition(async () => { hydrateRoot(document, <StrictMode><RSCHydratedRouter {...props} /></StrictMode>, { /* Options */ }); }); });

unstable_getRSCStream purpose and usage

unstable_getRSCStream retrieves the prerendered RSC stream for hydration. The stream is usually passed directly to your react-server-dom-xyz/client's createFromReadableStream function.

unstable_getRSCStream function signature and return type

The function unstable_getRSCStream takes no parameters and returns a ReadableStream that contains the RSC (React Server Components) data for hydration. The full signature is: function getRSCStream(): ReadableStream

unstable_routeRSCServerRequest renderHTML parameter

The renderHTML parameter is a function that receives getPayload (a function returning DecodedPayload) and options object. The options object contains nonce (optional string), onError (function taking unknown error and returning string or undefined), and onHeaders (function taking Headers). renderHTML should return ReadableStream<Uint8Array> or Promise<ReadableStream<Uint8Array>>.

unstable_routeRSCServerRequest signature and parameters

unstable_routeRSCServerRequest is an async function that routes incoming Request objects to the RSC server and proxies responses for data/resource requests or renders to HTML for document requests. It takes an object with: request (Request, required), serverResponse (Response, required), createFromReadableStream (SSRCreateFromReadableStreamFunction, required), renderHTML (function, required), hydrate (boolean, optional, defaults to true), nonce (string, optional). It returns Promise<Response>.

unstable_routeRSCServerRequest createFromReadableStream parameter

The createFromReadableStream parameter is the react-server-dom-xyz/client's createFromReadableStream function, used to decode payloads from the server. This is a required parameter of type SSRCreateFromReadableStreamFunction.

unstable_routeRSCServerRequest serverResponse parameter

The serverResponse parameter is a Response or partial response generated by the RSC handler containing a serialized unstable_RSCPayload. This is a required parameter.

unstable_routeRSCServerRequest hydrate parameter

The hydrate parameter is an optional boolean that determines whether to hydrate the server response with the RSC payload. It defaults to true.

unstable_routeRSCServerRequest nonce parameter

The nonce parameter is an optional string used as a nonce attribute for inline scripts generated while rendering the HTML document. It follows the MDN HTML nonce global attribute specification.

unstable_routeRSCServerRequest return type

unstable_routeRSCServerRequest returns a Promise<Response> that either contains the RSC payload for data requests, or renders the HTML for document requests.

unstable_routeRSCServerRequest example usage

Example showing how to use unstable_routeRSCServerRequest: ```tsx import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr"; import * as ReactDomServer from "react-dom/server.edge"; import { unstable_RSCStaticRouter as RSCStaticRouter, unstable_routeRSCServerRequest as routeRSCServerRequest, } from "react-router"; routeRSCServerRequest({ request, serverResponse, createFromReadableStream, nonce, async renderHTML(getPayload, options) { const payload = getPayload(); return await renderHTMLToReadableStream( <RSCStaticRouter getPayload={getPayload} nonce={options.nonce} />, { ...options, bootstrapScriptContent, formState: await payload.formState, } ); }, }); ```

unstable_matchRSCServerRequest function signature

unstable_matchRSCServerRequest is an async function that matches routes to a Request and returns a Response encoding an unstable_RSCPayload for RSC-enabled client routers. It accepts a single options object parameter with the following properties: allowedActionOrigins (string[] optional), createTemporaryReferenceSet (required function), basename (string optional), decodeReply (DecodeReplyFunction optional), requestContext (RouterContextProvider optional), routeDiscovery (RouteDiscovery optional), loadServerAction (LoadServerActionFunction optional), decodeAction (DecodeActionFunction optional), decodeFormState (DecodeFormStateFunction optional), clientVersion (string optional), onError (error handler optional), request (Request required), routes (RSCRouteConfigEntry[] required), generateResponse (function required). It returns a Promise that resolves to a Response containing RSC data for hydration.

unstable_matchRSCServerRequest.allowedActionOrigins parameter

The allowedActionOrigins parameter is an optional string array that defines origin patterns allowed to execute actions.

unstable_matchRSCServerRequest.createTemporaryReferenceSet parameter

The createTemporaryReferenceSet parameter is a required function that returns a temporary reference set for the request, used to track temporary references in the RSC stream.

unstable_matchRSCServerRequest.basename parameter

The basename parameter is an optional string that specifies the basename to use when matching the request.

unstable_matchRSCServerRequest.decodeAction parameter

The decodeAction parameter is an optional DecodeActionFunction from your react-server-dom-xyz/server package, responsible for loading a server action.

unstable_matchRSCServerRequest.decodeFormState parameter

The decodeFormState parameter is an optional function responsible for decoding form state for progressively enhanceable forms with React's useActionState using your react-server-dom-xyz/server's decodeFormState.

unstable_matchRSCServerRequest.decodeReply parameter

The decodeReply parameter is an optional DecodeReplyFunction from your react-server-dom-xyz/server package, used to decode the server function's arguments and bind them to the implementation for invocation by the router.

unstable_matchRSCServerRequest.generateResponse parameter

The generateResponse parameter is a required function responsible for using renderToReadableStream to generate a Response encoding the unstable_RSCPayload. It receives a match parameter of type RSCMatch and an object containing onError (a function) and temporaryReferences (unknown), and must return a Response.

unstable_matchRSCServerRequest.loadServerAction parameter

The loadServerAction parameter is an optional LoadServerActionFunction from your react-server-dom-xyz/server package, used to load a server action by ID.

unstable_matchRSCServerRequest.clientVersion parameter

The clientVersion parameter is an optional string representing a version derived from the client build output, used to detect stale clients during lazy route discovery.

unstable_matchRSCServerRequest.onError parameter

The onError parameter is an optional error handler function that will be called with any errors occurring during request processing.

unstable_matchRSCServerRequest.request parameter

The request parameter is a required Request object to match against the routes.

unstable_matchRSCServerRequest.requestContext parameter

The requestContext parameter is an optional RouterContextProvider instance that should be created per request and passed to actions, loaders, and middleware.

unstable_matchRSCServerRequest.routeDiscovery parameter

The routeDiscovery parameter is an optional RouteDiscovery configuration used to determine how the router should discover new routes during navigations.

Give your agent this brain