From 7110596bca775c3fb3eea2a6d81d3b6d0eece043 Mon Sep 17 00:00:00 2001 From: Matt Brophy Date: Mon, 24 Apr 2023 15:55:49 -0400 Subject: [PATCH] Clean up useRoutes RouterProvider detection (#10389) --- packages/react-router/lib/components.tsx | 5 ++++- packages/react-router/lib/hooks.tsx | 16 ++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/react-router/lib/components.tsx b/packages/react-router/lib/components.tsx index 0c2186c830..47b5266db8 100644 --- a/packages/react-router/lib/components.tsx +++ b/packages/react-router/lib/components.tsx @@ -41,6 +41,7 @@ import { useOutlet, useRoutes, _renderMatches, + useRoutesImpl, } from "./hooks"; export interface RouterProviderProps { @@ -132,7 +133,9 @@ function DataRoutes({ }: { routes: DataRouteObject[]; }): React.ReactElement | null { - return useRoutes(routes); + let state = React.useContext(DataRouterStateContext); + invariant(state, "No Router state available for DataRoutes"); + return useRoutesImpl(routes, undefined, state); } export interface MemoryRouterProps { diff --git a/packages/react-router/lib/hooks.tsx b/packages/react-router/lib/hooks.tsx index ce5353b68b..e21e533195 100644 --- a/packages/react-router/lib/hooks.tsx +++ b/packages/react-router/lib/hooks.tsx @@ -311,6 +311,15 @@ export function useResolvedPath( export function useRoutes( routes: RouteObject[], locationArg?: Partial | string +): React.ReactElement | null { + return useRoutesImpl(routes, locationArg); +} + +// Internal implementation with accept optional param for RouterProvider usage +export function useRoutesImpl( + routes: RouteObject[], + locationArg?: Partial | string, + dataRouterState?: RemixRouter["state"] ): React.ReactElement | null { invariant( useInRouterContext(), @@ -320,8 +329,6 @@ export function useRoutes( ); let { navigator } = React.useContext(NavigationContext); - let dataRouterContext = React.useContext(DataRouterContext); - let dataRouterStateContext = React.useContext(DataRouterStateContext); let { matches: parentMatches } = React.useContext(RouteContext); let routeMatch = parentMatches[parentMatches.length - 1]; let parentParams = routeMatch ? routeMatch.params : {}; @@ -434,10 +441,7 @@ export function useRoutes( }) ), parentMatches, - // Only pass along the dataRouterStateContext when we're rendering from the - // RouterProvider layer. If routes is different then we're rendering from - // a descendant tree - dataRouterContext?.router.routes === routes ? dataRouterStateContext : null + dataRouterState ); // When a user passes in a `locationArg`, the associated routes need to