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

useActionData returns action data or undefined

useActionData returns the data returned from the route's action function, or undefined if no action has been called. This data comes from the most recent POST navigation form submission.

useActionData hook signature

useActionData is a generic hook with signature function useActionData<T = any>(): SerializeFrom<T> | undefined. It takes no parameters and returns the serialized action data typed as T, or undefined if no action has been called.

useActionData example with Form submission

Example usage: import { Form, useActionData } from "react-router"; export async function action({ request }) { const body = await request.formData(); const name = body.get("visitorsName"); return { message: `Hello, ${name}` }; } export default function Invoices() { const data = useActionData(); return ( <Form method="post"> <input type="text" name="visitorsName" /> {data ? data.message : "Waiting..."} </Form> ); }

useBeforeUnload purpose

useBeforeUnload sets up a callback to be fired on the Window's beforeunload event, allowing you to run code when the user is about to leave the page.

useBeforeUnload options.capture parameter

The options object for useBeforeUnload accepts a capture property of type boolean. When capture is true, the event will be captured during the capture phase. The default value is false.

useBeforeUnload callback parameter

The callback parameter is a function that receives a BeforeUnloadEvent and can return any value. It is fired when the Window's beforeunload event is triggered.

useBeforeUnload hook signature and return type

useBeforeUnload is a hook that takes a callback function and optional options object, and returns void. The callback receives a BeforeUnloadEvent parameter. The signature is: function useBeforeUnload(callback: (event: BeforeUnloadEvent) => any, options?: { capture?: boolean }): void

useFetcher reset method

The fetcher object has a reset method that clears the fetcher's state.

useFetcher data property

The fetcher object has a data property that contains the data returned from the action or loader function.

useFetcher submit method with data object

The fetcher object has a submit method that can be called with a data object and options including method and encType. Example: fetcher.submit(someData, { method: 'post', encType: 'application/json' })

useFetcher basic example

import { useFetcher } from 'react-router' function SomeComponent() { let fetcher = useFetcher() // states are available on the fetcher fetcher.state // 'idle' | 'loading' | 'submitting' fetcher.data // the data returned from the action or loader // render a form <fetcher.Form method='post' /> // load data fetcher.load('/some/route') // submit data fetcher.submit(someFormRef, { method: 'post' }) fetcher.submit(someData, { method: 'post', encType: 'application/json' }) // reset fetcher fetcher.reset() }

useFetcher load method

The fetcher object has a load method that can be called with a route path to load data from that route without navigation. Example: fetcher.load('/some/route')

useFetcher Form component

The fetcher object includes a Form component (accessed as fetcher.Form) that can be rendered with method and other standard form attributes to submit data without navigation.

useFetcher state property

The fetcher object has a state property that returns one of three values: 'idle', 'loading', or 'submitting'.

useFetcher submit method with form reference

The fetcher object has a submit method that can be called with a form reference and options object. Example: fetcher.submit(someFormRef, { method: 'post' })

useFetcher purpose and use cases

useFetcher is useful for creating complex, dynamic user interfaces that require multiple, concurrent data interactions without causing a navigation. Fetchers track their own independent state and can be used to load data, submit forms, and interact with action and loader functions.

useFetcher hook signature and return type

useFetcher is a hook with the signature: function useFetcher<T = any>(options?: { key?: string }): FetcherWithComponents<SerializeFrom<T>>. It accepts an optional options object with an optional key property of type string. It returns a FetcherWithComponents object.

useFetcher key option for shared state

The key option in useFetcher allows you to identify a fetcher with a custom string. When the same key is used in multiple components throughout the app, those components will access the same fetcher and share its state. If no key is provided, useFetcher generates a unique fetcher scoped to that component.

useBlocker hook signature and return type

useBlocker is a hook with signature: function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker. It returns a Blocker object that manages navigation blocking state and actions.

useBlocker shouldBlock parameter

The shouldBlock parameter for useBlocker accepts either a boolean or a BlockerFunction. The function format receives a single object parameter containing currentLocation, nextLocation, and historyAction of the potential navigation, and returns a boolean indicating whether the navigation should be blocked.

useBlocker boolean version usage

useBlocker can be called with a simple boolean value: let blocker = useBlocker(value !== ""); This blocks navigation whenever the condition is true.

Blocker object structure and properties

The Blocker object returned by useBlocker has the following properties: state (unblocked, blocked, or proceeding), location (represents the Location being blocked or proceeded to), proceed() method (call when blocked to proceed to the blocked location), and reset() method (call when blocked to return to unblocked state and stay at current location).

useBlocker function version usage

useBlocker can be called with a BlockerFunction: let blocker = useBlocker(({ currentLocation, nextLocation, historyAction }) => value !== "" && currentLocation.pathname !== nextLocation.pathname); This provides access to navigation details for more complex blocking logic.

useBlocker example with ImportantForm component

import { useCallback, useState } from "react"; import { BlockerFunction, useBlocker } from "react-router"; export function ImportantForm() { const [value, setValue] = useState(""); const shouldBlock = useCallback<BlockerFunction>( () => value !== "", [value] ); const blocker = useBlocker(shouldBlock); return ( <form onSubmit={(e) => { e.preventDefault(); setValue(""); if (blocker.state === "blocked") { blocker.proceed(); } }} > <input name="data" value={value} onChange={(e) => setValue(e.target.value)} /> <button type="submit">Save</button> {blocker.state === "blocked" ? ( <> <p style={{ color: "red" }}> Blocked the last navigation to </p> <button type="button" onClick={() => blocker.proceed()} > Let me through </button> <button type="button" onClick={() => blocker.reset()} > Keep me here </button> </> ) : blocker.state === "proceeding" ? ( <p style={{ color: "orange" }}> Proceeding through blocked navigation </p> ) : ( <p style={{ color: "green" }}> Blocker is currently unblocked </p> )} </form> ); } This example demonstrates using useBlocker with a form that prevents navigation when the form has unsaved data (value !== ""), and provides buttons to either proceed with the navigation or reset the blocker to stay on the current page.

useBlocker does not handle hard-reloads or cross-origin navigations

useBlocker allows blocking navigations within the SPA and presenting a confirmation dialog, but it does not handle hard-reloads or cross-origin navigations.

Blocker state values

The blocker.state property has three possible values: unblocked (blocker is idle and has not prevented any navigation), blocked (blocker has prevented a navigation), and proceeding (blocker is proceeding through from a blocked navigation).

useFetchers basic usage example

Example: import { useFetchers } from "react-router"; function SomeComponent() { const fetchers = useFetchers(); fetchers[0].formData; // FormData fetchers[0].state; // etc. // ... }

useFetchers purpose and use case

useFetchers is useful for components throughout the app that did not create the fetchers but want to use their submissions to participate in optimistic UI. It returns all in-flight fetchers.

useFetchers return array structure

useFetchers returns an array of all in-flight Fetchers. Each Fetcher in the array has a unique key property in addition to standard Fetcher properties.

useFetchers hook signature and return type

useFetchers is a hook that returns an array of all in-flight Fetcher objects. The function signature is: function useFetchers(): (Fetcher & { key: string; })[].

useFormAction example usage

Example: import { useFormAction } from 'react-router'; function SomeComponent() { let action = useFormAction(); let destroyAction = useFormAction('destroy'); } The first call returns the closest route URL, the second appends 'destroy' to the closest route URL.

useFormAction return value

useFormAction returns a string that represents the resolved action URL.

useFormAction options.relative parameter

The options.relative parameter is optional and specifies the relative routing type to use when resolving the action. It defaults to 'route'.

useFormAction action parameter

The action parameter is optional and specifies the action to append to the closest route URL. It defaults to the closest route URL if not provided.

useFormAction basename behavior

The useFormAction hook adds a basename if your app specifies one, so that it can be used with raw form elements in a progressively enhanced way. If using this to provide an action to Form or fetcher.submit, you will need to remove the basename since both of those will prepend it internally.

useFormAction signature

useFormAction has the signature: function useFormAction(action?: string, { relative }: { relative?: RelativeRoutingType } = {}): string

useFormAction hook purpose

The useFormAction hook resolves the URL to the closest route in the component hierarchy instead of the current URL of the app. It is used internally by Form to resolve the action to the closest route, but can be used generically as well.

useHref return value

useHref returns the resolved href as a string.

useHref example usage

import { useHref } from 'react-router'; function SomeComponent() { let href = useHref('some/where'); // '/resolved/some/where' }

useHref to parameter

The 'to' parameter in useHref is the path to resolve.

useHref hook signature

useHref is a hook that resolves a URL against the current Location. It takes a parameter 'to' of type 'To' and an optional options object with a 'relative' property of type 'RelativeRoutingType'. It returns a string.

useHref relative option

The 'relative' option in useHref defaults to 'route' so routing is relative to the route tree. Set it to 'path' to make relative routing operate against path segments.

useInRouterContext purpose

useInRouterContext is used to ensure that a component is being used within a Router context. This is useful for validation and preventing misuse of components that depend on router functionality.

useInRouterContext hook signature and return type

useInRouterContext is a hook that takes no arguments and returns a boolean. It returns true if the component is a descendant of a Router component, and false otherwise.

useLoaderData with TypeScript

To type useLoaderData in TypeScript, pass the loader function type as a generic parameter: useLoaderData<typeof loader>(). This ensures the return type matches what the loader function returns.

useLoaderData hook signature

useLoaderData is a hook with signature function useLoaderData<T = any>(): SerializeFrom<T>. It takes no arguments and returns SerializeFrom<T>.

useLoaderData example

Example usage: import { useLoaderData } from "react-router"; export async function loader() { return await fakeDb.invoices.findAll(); } export default function Invoices() { let invoices = useLoaderData<typeof loader>(); }

useLoaderData returns loader data

useLoaderData returns the data from the closest route loader or clientLoader function. The hook retrieves data that was previously loaded by the route's loader or clientLoader and makes it available to the component.

useLocation signature and return type

The useLocation hook has the signature: function useLocation(): Location. It takes no parameters and returns a Location object representing the current route location.

useLocation hook returns current Location object

useLocation is a React hook that returns the current Location object. It can be used to perform side effects whenever the location changes, such as triggering analytics events.

useLocation example with side effect

import * as React from 'react' import { useLocation } from 'react-router' function SomeComponent() { let location = useLocation() React.useEffect(() => { // Google Analytics ga('send', 'pageview') }, [location]); return ( // ... ); } This example shows how to use useLocation to trigger a Google Analytics pageview event whenever the location changes.

useLinkClickHandler 'to' parameter

The 'to' parameter accepts the URL to navigate to. It can be a string or a partial Path object.

useLinkClickHandler options: target

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

useLinkClickHandler options: state

The state option has type any. It specifies the state to add to the History entry for this navigation. Defaults to undefined.

useLinkClickHandler options: preventScrollReset

The preventScrollReset option has type boolean. It determines whether to prevent the scroll position from being reset to the top of the viewport on completion of navigation when using the ScrollRestoration component. Defaults to false.

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.

useLinkClickHandler hook signature and return type

useLinkClickHandler is a generic function that takes a type parameter E extending Element, defaulting to HTMLAnchorElement. It returns a click handler function with signature (event: React.MouseEvent<E, MouseEvent>) => void. This handler can be used in custom Link components to replicate the built-in Link click behavior.

useLinkClickHandler options: relative

The relative option has type RelativeRoutingType. It sets the relative routing type to use for the link. Defaults to 'route'.

useLinkClickHandler options: viewTransition

The viewTransition option has type boolean. It enables a View Transition API for this navigation. To apply specific styles during the transition, use useViewTransitionState. Defaults to false.

Give your agent this brain