Skip to content

Commit 1116190

Browse files
committed
POC optimization for matchRoutes
1 parent 8cfb4a7 commit 1116190

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/react-router/lib/hooks.tsx

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as React from "react";
22
import type {
3+
AgnosticRouteMatch,
34
Blocker,
45
BlockerFunction,
56
Location,
@@ -445,7 +446,12 @@ export function useRoutesImpl(
445446
remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
446447
}
447448

448-
let matches = matchRoutes(routes, { pathname: remainingPathname });
449+
let matches =
450+
dataRouterState &&
451+
dataRouterState.matches &&
452+
dataRouterState.matches.length > 0
453+
? (dataRouterState.matches as AgnosticRouteMatch<string, RouteObject>[])
454+
: matchRoutes(routes, { pathname: remainingPathname });
449455

450456
if (__DEV__) {
451457
warning(

packages/router/router.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,7 @@ export function createRouter(init: RouterInit): Router {
829829
let initialScrollRestored = init.hydrationData != null;
830830

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

834835
if (initialMatches == null && !patchRoutesOnNavigationImpl) {
@@ -874,6 +875,7 @@ export function createRouter(init: RouterInit): Router {
874875
init.history.location.pathname
875876
);
876877
if (fogOfWar.active && fogOfWar.matches) {
878+
initialMatchesIsFOW = true;
877879
initialMatches = fogOfWar.matches;
878880
}
879881
}
@@ -1510,7 +1512,14 @@ export function createRouter(init: RouterInit): Router {
15101512

15111513
let routesToUse = inFlightDataRoutes || dataRoutes;
15121514
let loadingNavigation = opts && opts.overrideNavigation;
1513-
let matches = matchRoutes(routesToUse, location, basename);
1515+
let matches =
1516+
opts?.initialHydration &&
1517+
state.matches &&
1518+
state.matches.length > 0 &&
1519+
!initialMatchesIsFOW
1520+
? // `matchRoutes()` has already been called if we're in here via `router.initialize()`
1521+
state.matches
1522+
: matchRoutes(routesToUse, location, basename);
15141523
let flushSync = (opts && opts.flushSync) === true;
15151524

15161525
let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);

0 commit comments

Comments
 (0)