React Router navigation
Read this when changing route-level motion or navigation.
Router APIs
Check the installed types before using these. Minimum versions in parentheses; modes in brackets where an API is not in all three.
<Link to replace state preventScrollReset viewTransition reloadDocument mask onClick>: a real<a>. ItsonClickruns before the router's handler, andevent.preventDefault()there cancels that one navigation while thehref, prefetch handlers, anddiscoverstay intact.prefetchanddiscoverexist only in framework mode;preventScrollResetandviewTransitiononly in framework and data mode.<NavLink>:LinkplusisActive,isPending[framework, data], andisTransitioning(only when the link setsviewTransition) as render props, andactive,pending,transitioningclasses.useNavigate():navigate(to, { replace, state, relative, preventScrollReset, viewTransition, flushSync, mask })ornavigate(delta). In framework and data mode it returns a promise that resolves when the navigation completes; in declarative mode it returns nothing.useBlocker(shouldBlock)(6.19) [framework, data]: the only hold on a navigation. See below.useNavigation()[framework, data]:stateisidle,loading, orsubmitting;locationis the destination while pending;formMethod,formAction, andformDatadescribe a submission. It does not exposehistoryAction.useLocation():pathname,search,hash,state,key.keychanges on every navigation, including one to the same URL, and isdefaulton the first document load.useNavigationType():POP,PUSH, orREPLACEfor how the current location was reached.useViewTransitionState(to)(6.27) [framework, data]: true while a view transition runs andtomatches either side of it by pathname.<ScrollRestoration getKey>[framework, data]: render once, before<Scripts>.useBeforeUnload(cb): the document unload. It cannot be delayed.<Form>GET submissions,<Navigate>, andredirectfrom a loader or action are navigations.useFetcheris not:navigation.statestaysidleand the fetcher carries its ownstate.
Keep <Link> for every internal link so href, prefetching, and NavLink state keep working. Wrap it in a project-local transition-aware Link only when the outro must start on click without a blocker.
Page lifecycle
mount → initial state → intro → settled → outro → end state → unmount
- Initial state. The incoming route has committed or been reused in place, its final size is reserved, measurements are taken, and start values are set before anything is shown.
- Intro. Reveal the route and play one timeline to the final layout.
- Settled. Clear temporary styles. CSS owns the page. Everything is interactive.
- Outro. The outgoing route stays mounted while the router waits on the blocker, or before the navigation is issued. Stop competing component animations and play one outro timeline.
- End state. Finalize outgoing targets and run completion once while still mounted. Call
proceed()ornavigate. The outgoing tree goes away when the incoming one commits.
A controller may track internal states like waiting or preparing, but they serve these five phases.
Store the phase in React state or a ref owned by the boundary and render it as a data attribute on the route container, so CSS and tests can read it.
Outro before navigation: the blocker
There is no leave hook. useBlocker takes a boolean or ({ currentLocation, nextLocation, historyAction }) => boolean and returns a blocker with state (unblocked, blocked, proceeding), location, proceed(), and reset().
- The router checks the blocker before it touches history or runs a loader. While blocked the URL is unchanged, nothing has been fetched, and the old route is live and interactive. This is where the outro runs.
proceed()moves the blocker toproceedingand re-issues the same navigation with the same options:replace,state,preventScrollReset,viewTransition,mask. The router skips the blocker function whileproceeding, so no app-side guard is needed. Every blocker returns tounblockedwhen the navigation completes. From 8.2 a revalidation no longer clears a blocked state.- The pattern: return true for every non-
POPnavigation whose destination is a different screen; an effect onblocker.state === "blocked"starts the outro towardblocker.location; the end callback callsproceed(). Callreset()for a destination the design rejects, such as the current pathname. - A router supports one blocker. Registering a second logs a warning and the last one wins, and a blocker inside a route component is deleted when that route unmounts. Register it once in the boundary that outlives every navigation.
- Not covered: the initial document load, hard reloads, cross-origin URLs,
reloadDocumentlinks, and document unload. Those aregsap-vanillaterritory or cannot be delayed at all. A redirect returned by a loader or action happens inside a navigation that already passed the blocker; treat its destination as unrequested. POPis blockable but costly. The router restores the URL at once with a reversehistory.go, which flashes the destination in the address bar, andproceed()repeats the pop after that restore. A pop onto history the router did not create cannot be blocked at all. Return false forhistoryAction === "POP"and give back and forward the intro-only path.- Two rapid clicks: the second navigation runs the blocker function again. If it blocks, the blocker retargets:
blocker.locationandproceednow belong to the second destination and the hook returns a new object, so the effect runs again. Decide which wins. Last click wins by letting the outro keep running and calling the current blocker'sproceedat end state. First click wins by capturingproceedwhen the outro starts and calling that one. That capture is safe because eachproceedcloses over its own destination and options and re-issues that navigation whateverblocker.locationsays by then. Never start a second outro. - Do not gate the blocker function on your own lock. Returning
falsewhile an outro runs looks like "one navigation at a time" but does the opposite: the router runs the function for the second click,falselets that navigation proceed under the running outro, and the second destination wins. Keep returningtruefor every requested navigation and enforce the lock by choosing whichproceedto call. - Type the function as
BlockerFunctionwhen wrapping it inuseCallback, or its destructured parameters lose their contextual type and fail strict type checks. - The cost of the blocker path: loaders run only after
proceed(), so the end state sits on screen until the destination loads. Setprefetch="intent"on links in framework mode so data and modules are already cached, and cover the route container from end state until the incoming route is prepared.useNavigation().stateisloadingacross the gap andlocation.keychanges at commit.
A killed timeline never resolves its promise. Wrap await in a helper that also resolves on onInterrupt and returns whether the timeline completed, so an interrupted outro still reaches proceed() or reset(). A blocked navigation whose outro never finishes leaves the app stuck on the old page with the link apparently dead.
GSAP's ticker stops in a hidden tab. Race the outro against a timeout so a click from a background tab still navigates.
Outro before navigation: the transition-aware Link
This works in every mode and is the only option in declarative mode. Wrap <Link> or <NavLink>, forward unrelated props, and pass an onClick that:
- Calls the caller's
onClickfirst and stops if it prevented default. - Leaves native the clicks the router itself leaves native: non-primary buttons, modifier keys, a
targetother than_self, external URLs,reloadDocument, and hash-only or same-location links. - Calls
event.preventDefault(), runs the outro on the live page, then callsnavigate(to, { replace, state, preventScrollReset, viewTransition, mask, relative })with the Link's own props.
The href, prefetch handlers, discover, and NavLink state survive because the anchor is still React Router's. What is lost: the automatic replace when the URL is unchanged (compute it), useTransitions wrapping (call navigate inside startTransition and return its promise), and coverage: <Form>, <Navigate>, redirects, and navigate calls elsewhere bypass the wrapper. Add a navigate helper for buttons. If a blocker also exists, the re-issued navigate is a fresh navigation the blocker will see; gate the blocker function with a ref the helper sets before navigating and clears after.
A custom <a> built on useLinkClickHandler also works but drops prefetch, discover, and NavLink state. Use a document-level click listener only when replacing existing links is impractical; it is a retrofit, not the default.
The link path starts the outro on click and holds the URL like the blocker does, and has the same swap gap, since loaders run after the outro.
One navigation at a time
- Hold a lock from the first accepted destination through outro, cover, and commit. With a blocker the router retargets on a second click; without one the wrapper must ignore or record later clicks itself.
- Release the lock when the incoming intro starts, not when it ends: a click during the intro must kill the intro and start the outro from current values, and holding the lock through the intro leaves every link dead until it finishes.
- A
POPduring an outro is not blocked. Kill the outro so its promise settles, drop the pending destination, and let the history navigation take the intro-only path. - Repeated clicks must not create competing navigations or timelines.
Two kinds of navigation
- Requested (a link the boundary intercepted, the navigate helper, a blocked
Link,Form, ornavigate): the full lifecycle. The outgoing page plays its outro on live DOM, the router loads, the incoming page prepares behind the cover and plays its intro. - Unrequested (
POP, redirects,<Navigate>andnavigatecalls that bypass the helper, a fetcher revalidation that replaces content): the tree changes without an outro. Run initial state and intro only, without travel. Keep the shell stable. Optionally give these aviewTransitioncrossfade so the swap is not a hard cut.
Do not keep a copy of the old React tree to fake an outro for unrequested navigation. Support fewer outro paths instead.
Back and forward
useNavigationType()reportsPOPafter commit. A blocker function seeshistoryAction === "POP"before it. Neither runs an outro.POPis also the navigation type of every document's first location. Tell a real history arrival apart withlocation.key !== "default", or, on a document's first render, withperformance.getEntriesByType("navigation")[0]?.type === "back_forward".<ScrollRestoration>restores the saved position in a layout effect at commit. A page'suseGSAPlayout effect runs in the same commit, so write initial state there but defer the step frominitialtointroby a microtask; the intro then starts after restoration. Refresh ScrollTrigger at the same point, and reveal-on-scroll targets above the restored position must not stay hidden.- If the pair of pathnames was navigated with
viewTransition, the router remembers it in session storage and replays the transition on the pop with the roles reversed. Design the intro-only path to look right under that crossfade or morph. - A route reached by back that was reused rather than remounted still holds settled values. Write initial state explicitly.
- A bfcache restore runs no router code except re-enabling manual scroll restoration. Leave the page readable whenever it can be unloaded.
Overlapping the old and new page
The router renders one route tree. An effect that needs both on screen at once has two honest options:
- The browser. A
viewTransitionnavigation snapshots both trees.useViewTransitionStateor a class on the root gives the CSS the direction and the names. - A DOM snapshot. After the outgoing page reaches end state and before
proceed(), deep-clone the route container into a fixed layer: strip ids and every data attribute your lifecycle selects on, setinertandaria-hidden, position it at the container's document offset shifted by the scroll. Proceed with no cover. The incoming intro reveals the new page over the clone and removes it at settle, on a ready timeout, onPOP, and at the start of any new navigation.
The clone is a static picture, not a React tree: nothing in it updates, nothing in it is reachable, and it is gone before the page is interactive.
The swap gap and initial state
Between end state and the incoming intro, the old page sits at end state while loaders run and then unmounts as the new one commits. Cover the route container during that gap, inside the element that wraps route content and never fixed to the viewport, or the header and footer flash on every click. Uncover only after every incoming target has its size and start styles.
The initial state must occupy the same layout as the settled state. Prefer autoAlpha and transforms. Size images, media, masks, and async regions before the intro. If the effect changes geometry, reserve the settled size with a wrapper or measure both states before writing either.
The route container owns geometry during the swap: hold a stable height while trees exchange, or animate it between measured sizes on purpose; reserve scrollbar space if route height changes would shift it.
Server-rendered and prerendered HTML paints before hydration. Do not hide it unconditionally. If initial state must hide before first paint:
- Put an inline script first in
bodyin the root route'sLayoutexport, which wraps the app,HydrateFallback, andErrorBoundaryalike, that markshtmlas JavaScript-active. AddsuppressHydrationWarningtohtml, since the server HTML does not carry the attribute. - Add a CSS rule that hides intro targets only under that mark and only while the root is in its initial phase.
- Skip the mark under
prefers-reduced-motionso the page paints settled. - Keep the early failsafe active until preparation succeeds and the intro can run, not merely until a controller registers. Register rollback before setup, preserve the original deadline, and take the settled path after recovery. Follow Initialization and recovery.
- Register rollback before setup. Advance the phase only after start values and completion handlers are ready, in the same turn that starts the intro.
- Keep content readable without JavaScript. Omitting
<Scripts>is React Router's no-JavaScript mode, and the page must still read there. - Keep the swap cover separate from the first-paint rule.
ssr: false, data mode, and declarative mode without server rendering paint nothing before React. useGSAP runs in a layout effect on the client, so explicit set calls there land before the first paint and no pre-paint rule is needed. A HydrateFallback is a skeleton that appears only on the initial load; give it the settled geometry and let the route enter through the unrequested path when its data lands.
Do not rely only on inline styles: a context revert clears them during a swap. The cover must survive cleanup until the new tree is ready.
Pending state, loaders, and streaming
- The router awaits loaders before rendering the next route, so during
loadingthe outgoing page is mounted and interactive. Pending UI belongs there: a global indicator fromuseNavigation().location, orisPendingon theNavLinkthat was clicked. Do not start the outro fromnavigation.state; by then the navigation is already committed to happen. - A promise returned un-awaited from a loader streams.
<Await>inside<Suspense>, or React 19use, renders it when it lands, and afterstreamTimeoutit rejects. Treat each streamed region as a component with its own controller: explicit initial state on arrival, a short intro, settled, cleanup. Reserve its block size so arrival moves nothing. Query outro targets when the outro is built, not at setup, so content that streamed in after setup leaves with the page. clientLoaderruns in the browser on navigation and, withhydrate, on the initial load behindHydrateFallback. Neither changes the lifecycle; the route still commits once its data is ready.
Settled state, focus, and scroll
On intro completion, mark settled once, clear temporary transforms, visibility, and will-change, and do not keep the page inside an active timeline to hold values.
- React Router moves no focus and announces nothing on a route change. If navigation left focus on
body, move it to the route container or main heading after the intro, withtabIndex={-1}and a visible focus style. Do not steal focus from an active control. Add a live region if the product needs announcements. <ScrollRestoration>runs in a layout effect at commit: a saved position onPOP, the hash target when there is one, nothing whenpreventScrollResetwas set, otherwise the top. Submissions and revalidations leave scroll alone. It keys onlocation.keyby default;getKeywithpathnamerestores across repeat visits to the same path.- Keep that behavior. Do not add a second scroll reset unless the product needs it. Refresh ScrollTrigger after restoration, and after the intro if anything above a trigger changed height.
- Pass
preventScrollResetthrough the transition-aware Link and helper;proceed()already carries it.
Smooth scrolling
Follow Smooth scrolling for the contract; the animaxxing skill's references/recipes/smooth-scroll.md supplies the controls. React Router specifics:
- Create the scroller in the root route component, which outlives every client navigation, from
useGSAPor a layout effect with no dependencies, and destroy it in that cleanup. Keep the handle in a ref and share it through context, never module scope. StrictMode and Vite's Fast Refresh both rerun that effect; the cleanup'sdestroy()runs before the second create, so the pair leaves one scroller. In framework mode the root module is evaluated on the server, so the create stays inside the effect. A ScrollSmoother wrapper goes around<Outlet>in the root, with the chrome, the route cover, and any curtain outside it. - Outro.
stop()when the blocker blocks or the wrapper intercepts, before the outro timeline starts. - End state and swap. Still stopped through
proceed(), the loaders, and the commit.<ScrollRestoration>[framework, data] setshistory.scrollRestorationtomanual, saves positions perlocation.keyorgetKey, and applies its result in a layout effect at commit: the saved position onPOP, the hash target, nothing withpreventScrollReset, otherwise the top. Leave it on. - New page mounted. From the boundary's microtask after the commit, the same one that steps the page from initial to intro,
scrollTo(window.scrollY, { immediate: true })so the engine adopts what the router chose. The page's own layout effect shares the commit with the restore and can run before it. - Intro built.
resize()once the page's triggers exist, and again at settled if the intro changed height above a trigger. - Settled.
start(). Alsostart()wherever the lock releases without an intro:reset(), aPOPthat kills an outro, the ready timeout. - Declarative mode has no
<ScrollRestoration>: the router scrolls nowhere and the browser keepsautorestoration. Jump to the top yourself after aPUSHcommits and sync towindow.scrollYafter aPOP. - Same-page hash links stay native and instant;
<ScrollRestoration>scrolls the hash target into view at commit before it honorspreventScrollReset. To ease one, prevent default andscrollTo(hash)without navigating, then move focus to the target. - Recreate the scroller from the root when the app's motion setting changes.
Curtains, preloaders, and shared elements
All three follow Transition archetypes; the builders come from the animaxxing skill's references/recipes/page-covers.md and references/recipes/layout-flip.md.
- A curtain is the one cover allowed to span the chrome. Render its panels in the root route component after
<Outlet>and outside any ScrollSmoother wrapper, buildcurtain()once in the boundary's setup, and let it replace the route-area cover for the navigations that use it. The recipe's CSS keeps the panels hidden, so server HTML never paints them. - The blocker receives locations, not elements, so a link opts into the curtain through its
onClick: record a request keyed by its destination with the boundary, and let the blocker read it. Buildcover()on the shell's timeline, not inside the page'suseGSAPcontext, whose cleanup reverts every child; the page's end state waits for it (await coverTimeline). Callproceed()from its completion. The loaders, the pending gap the blocker path costs, and the commit all happen under the curtain, with the scroller stopped.reveal()starts from the incoming page's ready signal after the newlocation.keycommits. APOPgets no cover; one that arrives while covered, which the blocker function sees ashistoryAction === "POP", kills the outro, drops the destination, and reveals once the popped page is ready. A second click duringcover()retargets the blocker: keep covering and call the chosenproceedonce. A click duringreveal()callscover()again. Register the reveal with the boundary's recovery so a timed-out page never stays covered. - Preloader, framework mode with SSR or
prerender: decide in the rootLayout's inline script fromsessionStorageand set a root attribute. Server HTML cannot know the session, so render the markup unconditionally inLayout, which wraps the app,HydrateFallback, andErrorBoundaryalike, and show it only under that attribute in CSS. When the attribute is present the boundary buildspreloader(root), setsaria-busy="true"on the route container, and feedsprogress()fromdocument.fonts.ready, the hero image'sdecode(), and the first route's commit, which aclientLoaderwithhydratedelays behindHydrateFallback, each bounded by the deadline the same script armed.finish()overlaps the first intro while the page waits at initial state.ssr: falseprerenders the root shell too, so the same rule holds; data and declarative mode paint nothing before React, so the root can render it from asessionStorageread in its first render. The root never remounts on a client navigation, so it never shows again. - Shared elements: call
captureSharedin the blocker outro beforeproceed(), with no cover and noviewTransitionon that navigation, or the browser snapshots the element GSAP is about to morph. Keep the handoff in the boundary, keyed byblocker.location.pathname; reads must not consume it, since StrictMode runs the page setup twice. Clear it at settle, onreset(), on a retarget, and onPOP. PlayplayShared(state, target)from the ready microtask after the newlocation.keycommits, target explicit. APOPreplays a recorded view transition pair and carries no captured state, so leave the shared element unnamed and give history moves the ordinary intro.
Combining with View Transitions
Set viewTransition on the Link, Form, or navigate call. HydratedRouter supports it; in data mode RouterProvider must come from react-router/dom, which wires flushSync, or useViewTransitionState throws. The router calls document.startViewTransition around the state update at commit and records the pathname pair so a later pop replays it. GSAP runs before it, outro on live DOM before proceed(), and after it, intro on the new tree once the transition finishes. Keep their jobs separate:
- One engine per element per transition. A named morph and a GSAP tween on the same node fight, and a GSAP end state becomes the old snapshot. Leave a shared element lit at end state or skip the view transition for that navigation.
- Name only elements that morph.
useViewTransitionState(to)and theNavLinkisTransitioningrender prop are true only while that pair transitions, so use them to setviewTransitionNameand clear it after. - The router does not expose the
ViewTransitionobject.useViewTransitionStatereturns to false when the transition finishes; start GSAP on elements the browser touched from an effect on that flip, or keep them out of the intro. - A new navigation during a transition skips the active one and starts another. The GSAP lock must survive that.
proceed()keepsviewTransition, so the blocker path and the browser path compose: GSAP outro, then proceed, then the browser morphs at commit.- Add
::view-transition { pointer-events: none }so a running transition does not swallow clicks. - Where
startViewTransitionis missing the router updates plainly. Every GSAP path must run without it. - Reduced motion covers both: zero view transition durations in CSS and take the GSAP reduced path.
Cases to design for
- Navigation requested mid-intro.
- Two destinations clicked quickly, with the blocker retargeting.
- Back or forward with no outro, including mid-outro.
- A route reused with new params, and a search-param-only change.
- A
FormGET,<Navigate>, ornavigatecall that bypasses the wrapper. - A hash-only link, which is same-page.
- A redirect from a loader or action.
- An external link, a
reloadDocumentlink, and a document unload. - Split text or scroll plugins that changed the DOM before cleanup.
- Streamed data arriving after the intro.
- React development double-mounting the boundary.
Each case must end on one visible, interactive route with stable layout and no stale inline styles.