diff --git a/.changeset/route-lazy-fouc.md b/.changeset/route-lazy-fouc.md new file mode 100644 index 00000000000..46d44e63cf4 --- /dev/null +++ b/.changeset/route-lazy-fouc.md @@ -0,0 +1,5 @@ +--- +"@remix-run/react": patch +--- + +Fix FOUC on subsequent client-side navigations to route.lazy routes diff --git a/packages/remix-react/routes.tsx b/packages/remix-react/routes.tsx index c2e70447239..074b56b239d 100644 --- a/packages/remix-react/routes.tsx +++ b/packages/remix-react/routes.tsx @@ -131,22 +131,40 @@ export function createClientRoutes( id: route.id, index: route.index, path: route.path, - loader({ request }) { - if (!route.hasLoader) return null; - return fetchServerHandler(request, route); - }, - action({ request }) { - if (!route.hasAction) { - let msg = - `Route "${route.id}" does not have an action, but you are trying ` + - `to submit to it. To fix this, please add an \`action\` function to the route`; - console.error(msg); - return Promise.reject( - new ErrorResponse(405, "Method Not Allowed", new Error(msg), true) - ); + async loader({ request }) { + // Only prefetch links if we've been loaded into the cache, route.lazy + // will handle initial loads + let routeModulePromise = routeModulesCache[route.id] + ? prefetchStyleLinks(routeModulesCache[route.id]) + : Promise.resolve(); + try { + if (!route.hasLoader) return null; + return fetchServerHandler(request, route); + } finally { + await routeModulePromise; } + }, + async action({ request }) { + // Only prefetch links if we've been loaded into the cache, route.lazy + // will handle initial loads + let routeModulePromise = routeModulesCache[route.id] + ? prefetchStyleLinks(routeModulesCache[route.id]) + : Promise.resolve(); + try { + if (!route.hasAction) { + let msg = + `Route "${route.id}" does not have an action, but you are trying ` + + `to submit to it. To fix this, please add an \`action\` function to the route`; + console.error(msg); + return Promise.reject( + new ErrorResponse(405, "Method Not Allowed", new Error(msg), true) + ); + } - return fetchServerHandler(request, route); + return fetchServerHandler(request, route); + } finally { + await routeModulePromise; + } }, ...(routeModule ? // Use critical path modules directly