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

useLinkClickHandler options: target

The target option has type React.HTMLAttributeAnchorTarget. It sets the target attribute for the link. Defaults to undefined.

useLinkClickHandler options: replace

The replace option has type boolean. It determines whether to replace the current History entry instead of pushing a new one. Defaults to false.

useLinkClickHandler options: mask

The mask option has type To. It specifies a masked location to display in the browser instead of the router location. Defaults to undefined.

useMatch return value

useMatch returns a PathMatch object if the pattern matches the current URL, or null if it does not match.

useMatch use case

useMatch is useful for components that need to know active state, such as NavLink components.

useMatch pattern parameter

The useMatch hook accepts a pattern parameter of type PathPattern<Path> or Path. The pattern is matched against the current Location.

useMatch hook signature

useMatch is a function that takes a pattern parameter and returns either a PathMatch object or null. The function signature is: function useMatch<Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamParseKey<Path>> | null

useMatches properties

Each item in the array returned by useMatches contains the following properties: id (the route id), pathname (the portion of the URL the route matched), params (the parsed params from the URL), loaderData (the data from the loader), and handle (the route handle with any app specific data).

useMatches import statement

useMatches is imported from 'react-router': import { useMatches } from "react-router";

useMatches basic usage example

Basic usage of useMatches: import { useMatches } from "react-router"; function SomeComponent() { const matches = useMatches(); // matches[i].id // route id // matches[i].pathname // the portion of the URL the route matched // matches[i].params // the parsed params from the URL // matches[i].loaderData // the data from the loader // matches[i].handle // the route handle with any app specific data }

useMatches hook summary

useMatches returns the active route matches for the current route hierarchy. It is useful for accessing loaderData for parent and child routes, or the route handle property. This hook only works with a data router like createBrowserRouter, since they know the full route tree up front and can provide all current matches. useMatches will not match down into any descendant route trees since the router is not aware of descendant routes.

useMatches return type

useMatches returns an array of UIMatch objects: function useMatches(): UIMatch[]

useMatches with route handle

Pairing the route handle property with useMatches becomes very powerful because you can put whatever you want on a route handle and have access to that data via useMatches anywhere in the component tree. This is useful for implementing patterns like breadcrumbs.

useNavigation hook returns Navigation object

The useNavigation hook returns the current Navigation object, which defaults to an "idle" navigation when no navigation is in progress. The hook can be used to render pending UI such as a global spinner or to read FormData from a form navigation.

useNavigation hook example

Example usage of useNavigation: import { useNavigation } from "react-router"; function SomeComponent() { let navigation = useNavigation(); navigation.state; navigation.formData; }. This shows accessing the state and formData properties of the Navigation object.

useNavigation signature and return type

The useNavigation hook has the signature: function useNavigation(): UseNavigationResult. It takes no arguments and returns a Navigation object.

useNavigate hook signature and return type

The useNavigate hook has the signature `function useNavigate(): NavigateFunction`. It returns a navigate function for programmatic navigation.

useOutlet hook signature

useOutlet returns the element for the child route at the current level of the route hierarchy. The signature is: function useOutlet(context?: unknown): React.ReactElement | null. The context parameter is optional and is passed to the outlet.

useOutlet return value

useOutlet returns a React.ReactElement or null. It returns the child route element if child routes match at this level of the hierarchy, or null if no child routes match.

useOutlet context parameter

useOutlet accepts a context parameter of type unknown, which is optional. This context is passed to the outlet.

useNavigationType describes how router came to current location

useNavigationType returns the current Navigation action which describes how the router came to the current Location, either by a pop, push, or replace on the History stack.

useNavigationType hook signature and return type

useNavigationType is a hook with the signature: function useNavigationType(): NavigationType. It returns the current NavigationType, which is one of three values: "POP", "PUSH", or "REPLACE".

useParams signature and return type

useParams is a generic function with signature: function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>. It returns an object containing the dynamic route parameters as a readonly object.

useParams with single route parameter example

Example: Given a route /posts/:postId, access the parameter in a component with: import { useParams } from "react-router"; export default function Post() { let params = useParams(); return <h1>Post: {params.postId}</h1>; }

useParams catchall parameter example

Example accessing catchall: import { useParams } from "react-router"; export default function File() { let params = useParams(); let catchall = params["*"]; } Or with destructuring: export default function File() { let { "*": catchall } = useParams(); console.log(catchall); }

useParams with multiple route parameters

Route patterns can have multiple parameters such as /posts/:postId/comments/:commentId. All parameters are available in the params object returned by useParams.

useParams with multiple parameters example

Example: import { useParams } from "react-router"; export default function Post() { let params = useParams(); return ( <h1>Post: {params.postId}, Comment: {params.commentId}</h1> ); }

useParams with catchall parameters

Catchall parameters are defined with * in the route pattern, such as /files/*. The matched value is available in the params object using the "*" key.

useParams hook basic usage

useParams is a React Router hook that returns an object of key/value-pairs containing the dynamic route parameters from the current URL. Child routes inherit all params from their parent routes. For a route pattern like /posts/:postId matched by /posts/123, params.postId will be "123".

useOutletContext hook signature

useOutletContext is a generic hook with the signature: function useOutletContext<Context = unknown>(): Context. It returns the context value passed to the parent Outlet component.

useOutletContext basic example

Example showing useOutletContext basic usage: ```tsx // Parent route function Parent() { const [count, setCount] = React.useState(0); return <Outlet context={[count, setCount]} />; } // Child route import { useOutletContext } from "react-router"; function Child() { const [count, setCount] = useOutletContext(); const increment = () => setCount((c) => c + 1); return <button onClick={increment}>{count}</button>; } ``` This example shows a parent route managing count state in an Outlet context, and a child route accessing and updating it.

useOutletContext TypeScript pattern with custom hook

When using TypeScript, it is recommended that the parent component provide a custom hook for accessing the context value. This gives consumers better typings, allows control over consumers, and makes it clear who is consuming the context. The custom hook should call useOutletContext with a generic type parameter matching the context shape.

useOutletContext returns parent Outlet context

useOutletContext returns the context value that was passed to the parent route's Outlet component via its context prop. This allows child routes to access state or values managed by the parent route.

useOutletContext TypeScript example with custom hook

Example showing useOutletContext with TypeScript and a custom hook: ```tsx // src/routes/dashboard.tsx import { useState } from "react"; import { Outlet, useOutletContext } from "react-router"; import type { User } from "./types"; type ContextType = { user: User | null }; export default function Dashboard() { const [user, setUser] = useState<User | null>(null); return ( <div> <h1>Dashboard</h1> <Outlet context={{ user } satisfies ContextType} /> </div> ); } export function useUser() { return useOutletContext<ContextType>(); } ``` ```tsx // src/routes/dashboard/messages.tsx import { useUser } from "../dashboard"; export default function DashboardMessages() { const { user } = useUser(); return ( <div> <h2>Messages</h2> <p>Hello, {user.name}!</p> </div> ); } ``` This example shows a parent route providing typed context with a custom hook, which child routes can import and use with full type safety.

useResolvedPath relative routing modes

The 'relative' option controls how relative routing operates. When set to 'route' (the default), routing is relative to the route tree. When set to 'path', relative routing operates against path segments.

useResolvedPath example with relative path resolution

Example: if the user is at /dashboard/profile and useResolvedPath is called with '../accounts', it returns a Path object where pathname is '/dashboard/accounts', search is '', and hash is ''.

useResolvedPath resolves pathname against current location

useResolvedPath resolves the pathname of the given 'to' value against the current Location. It is similar to useHref, but returns a Path object instead of a string.

useResolvedPath hook signature and parameters

useResolvedPath is a hook that takes a 'to' parameter (type To) and an optional options object. The options object has a 'relative' property of type RelativeRoutingType that defaults to 'route'. The hook returns a Path object.

useResolvedPath returns Path object with pathname, search, and hash

The useResolvedPath hook returns a Path object containing three properties: pathname, search, and hash.

unstable_usePrompt stability warning

The unstable_usePrompt hook is experimental and subject to breaking changes in minor and patch releases. The unstable_ prefix will not be removed because this technique has many rough edges and behaves very differently (and sometimes incorrectly) across browsers if users click additional back/forward navigations while the confirmation dialog is open. Users should employ caution and carefully monitor release notes for relevant changes.

unstable_usePrompt hook signature

The unstable_usePrompt hook accepts an object with two properties: when (boolean | BlockerFunction) and message (string). It returns void.

unstable_usePrompt when parameter

The when parameter accepts either a boolean value or a BlockerFunction. If a function is provided, it receives an object with currentLocation and nextLocation properties, and should return a boolean indicating whether to block the navigation.

unstable_usePrompt message parameter

The message parameter is a string that will be shown in the browser's confirmation dialog when navigation is attempted.

unstable_usePrompt wrapper around useBlocker

The unstable_usePrompt hook is a wrapper around useBlocker that shows a window.confirm prompt to users instead of requiring developers to build a custom UI with useBlocker.

unstable_usePrompt example with form

Example showing how to use unstable_usePrompt to block navigation when data has been entered into a form: ```tsx function ImportantForm() { let [value, setValue] = React.useState(""); // Block navigating elsewhere when data has been entered into the input unstable_usePrompt({ message: "Are you sure?", when: ({ currentLocation, nextLocation }) => value !== "" && currentLocation.pathname !== nextLocation.pathname, }); return ( <Form method="post"> <label> Enter some important data: <input name="data" value={value} onChange={(e) => setValue(e.target.value)} /> </label> <button type="submit">Save</button> </Form> ); } ```

useRevalidator usage example with window focus

import { useRevalidator } from "react-router"; function WindowFocusRevalidator() { const revalidator = useRevalidator(); useFakeWindowFocus(() => { revalidator.revalidate(); }); return ( <div hidden={revalidator.state === "idle"}> Revalidating... </div> ); } This example shows calling revalidator.revalidate() on window focus and checking revalidator.state to conditionally display a message.

useRevalidator - when not to use it

Do not use useRevalidator for normal CRUD operations in response to user interactions. Instead use other APIs like useFetcher, Form, or useSubmit which handle revalidation automatically.

useRevalidator revalidate method

The revalidate method is a function that takes no arguments and returns Promise<void>. It manually triggers revalidation of page data.

useRevalidator state property

The state property reflects the current revalidation state and matches the DataRouter revalidation state type. It can be checked to determine if revalidation is in progress (not "idle").

useRevalidator purpose

useRevalidator is used to revalidate page data for reasons outside of normal data mutations, such as Window focus events or polling on an interval. Page data is already revalidated automatically after actions.

useRevalidator hook signature and return type

useRevalidator returns an object with two properties: revalidate (a function that returns Promise<void>) and state (a string matching DataRouter["state"]["revalidation"]).

useRouteError available modes

useRouteError is available in framework and data modes.

useRouteError usage example

The useRouteError hook is typically used in an ErrorBoundary component to access and display thrown errors. Example: export function ErrorBoundary() { const error = useRouteError(); return <div>{error.message}</div>; }

useRouteError hook signature and return type

useRouteError is a hook that returns unknown. It accesses the error thrown during an action, loader, or component render to be used in a route module ErrorBoundary.

useRouteError returns error from loading action or render

useRouteError returns the error that was thrown during route loading, action execution, or component rendering.

useRouteLoaderData hook signature

useRouteLoaderData is a hook with signature function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined. It accepts a routeId parameter as a string and returns the loader data for that route, or undefined if not found.

useRouteLoaderData purpose

useRouteLoaderData returns the loader data for a given route by route ID. The loader data is what was returned from the specified route's loader function.

useRouteLoaderData example

import { useRouteLoaderData } from "react-router"; function SomeComponent() { const { user } = useRouteLoaderData("root"); } // You can also specify your own route ID's manually in your routes.ts file: route("/", "containers/app.tsx", { id: "app" }) useRouteLoaderData("app");

unstable_useRouterState import

To use unstable_useRouterState, import it as: import { unstable_useRouterState as useRouterState } from "react-router";

unstable_useRouterState experimental warning

This API is experimental and subject to breaking changes in minor or patch releases. Users should pay very close attention to release notes for relevant changes.

Give your agent this brain