Skip to content

Optimization to avoid redundant calls to matchRoutes #12800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smooth-mangos-act.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Optimize route matching by skipping redundant `matchRoutes` calls when possible
7 changes: 4 additions & 3 deletions packages/react-router/__tests__/dom/ssr/components-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,10 @@ describe("<NavLink />", () => {

describe("<ServerRouter>", () => {
it("handles empty default export objects from the compiler", async () => {
let staticHandlerContext = await createStaticHandler([{ path: "/" }]).query(
new Request("http://localhost/")
);
let staticHandlerContext = await createStaticHandler([
{ id: "root", path: "/", children: [{ id: "empty", index: true }] },
]).query(new Request("http://localhost/"));

invariant(
!(staticHandlerContext instanceof Response),
"Expected a context"
Expand Down
8 changes: 7 additions & 1 deletion packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import type {
} from "./router/router";
import { IDLE_BLOCKER } from "./router/router";
import type {
AgnosticRouteMatch,
ParamParseKey,
Params,
PathMatch,
Expand Down Expand Up @@ -534,7 +535,12 @@ export function useRoutesImpl(
remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
}

let matches = matchRoutes(routes, { pathname: remainingPathname });
let matches =
dataRouterState &&
dataRouterState.matches &&
dataRouterState.matches.length > 0
? (dataRouterState.matches as AgnosticRouteMatch<string, RouteObject>[])
: matchRoutes(routes, { pathname: remainingPathname });

if (ENABLE_DEV_WARNINGS) {
warning(
Expand Down
11 changes: 10 additions & 1 deletion packages/react-router/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,7 @@ export function createRouter(init: RouterInit): Router {
let initialScrollRestored = init.hydrationData != null;

let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
let initialMatchesIsFOW = false;
let initialErrors: RouteData | null = null;

if (initialMatches == null && !patchRoutesOnNavigationImpl) {
Expand Down Expand Up @@ -882,6 +883,7 @@ export function createRouter(init: RouterInit): Router {
init.history.location.pathname
);
if (fogOfWar.active && fogOfWar.matches) {
initialMatchesIsFOW = true;
initialMatches = fogOfWar.matches;
}
} else if (initialMatches.some((m) => m.route.lazy)) {
Expand Down Expand Up @@ -1521,7 +1523,14 @@ export function createRouter(init: RouterInit): Router {

let routesToUse = inFlightDataRoutes || dataRoutes;
let loadingNavigation = opts && opts.overrideNavigation;
let matches = matchRoutes(routesToUse, location, basename);
let matches =
opts?.initialHydration &&
state.matches &&
state.matches.length > 0 &&
!initialMatchesIsFOW
? // `matchRoutes()` has already been called if we're in here via `router.initialize()`
state.matches
: matchRoutes(routesToUse, location, basename);
let flushSync = (opts && opts.flushSync) === true;

let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
Expand Down
Loading