Skip to content

Commit 59522ba

Browse files
authored
React 18 "React.use" webpack fix (#14113)
1 parent ee7d150 commit 59522ba

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

.changeset/rotten-foxes-deliver.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router": patch
3+
---
4+
5+
Adjust internal RSC usage of `React.use` to avoid Webpack compilation errors when using React 18

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@
125125
- gatzjames
126126
- gavriguy
127127
- Geist5000
128+
- GeoffKarnov
128129
- gesposito
129130
- gianlucca
130131
- gijo-varghese

packages/react-router/lib/rsc/server.ssr.tsx

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@ import { RSCRouterGlobalErrorBoundary } from "./errorBoundaries";
88
import { shouldHydrateRouteLoader } from "../dom/ssr/routes";
99
import type { RSCPayload } from "./server.rsc";
1010

11+
// Safe version of React.use() that will not cause compilation errors against
12+
// React 18 and will result in a runtime error if used (you can't use RSC against
13+
// React 18).
14+
const REACT_USE = "use";
15+
const useImpl = (React as any)[REACT_USE];
16+
17+
function useSafe<T>(promise: Promise<T> | React.Context<T>): T {
18+
if (useImpl) {
19+
return useImpl(promise);
20+
}
21+
throw new Error("React Router v7 requires React 19+ for RSC features.");
22+
}
23+
1124
export type SSRCreateFromReadableStreamFunction = (
1225
body: ReadableStream<Uint8Array>,
1326
) => Promise<unknown>;
@@ -196,8 +209,8 @@ export interface RSCStaticRouterProps {
196209
* @returns A React component that renders the {@link unstable_RSCPayload} as HTML.
197210
*/
198211
export function RSCStaticRouter({ getPayload }: RSCStaticRouterProps) {
199-
// @ts-expect-error - need to update the React types
200-
const payload = React.use(getPayload()) as RSCPayload;
212+
// Can be replaced with React.use when v18 compatibility is no longer required.
213+
const payload = useSafe(getPayload());
201214

202215
if (payload.type === "redirect") {
203216
throw new Response(null, {

0 commit comments

Comments
 (0)