Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [Flight] allow context providers from client modules (#35675) · react/react@3e00319 · GitHub
Skip to content

Commit 3e00319

Browse files
[Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module and render its Provider. Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling in mountLazyComponent so lazy-resolved Context types can be rendered. Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE were handled. Tested in the Flight fixture. ty bb claude Closes#35340 --------- Co-authored-by: Sophie Alpert <git@sophiebits.com>
1 parent 3419420 commit 3e00319

9 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎fixtures/flight/src/App.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from 'react';
22
import{renderToReadableStream}from'react-server-dom-unbundled/server';
33
import{createFromReadableStream}from'react-server-dom-webpack/client';
44
import{PassThrough,Readable}from'stream';
5-
5+
import{ClientContext,ClientReadContext}from'./ClientContext.js';
66
importContainerfrom'./Container.js';
77

88
import{Counter}from'./Counter.js';
@@ -235,6 +235,11 @@ export default async function App({prerender, noCache}) {
235235
<Foo>{dedupedChild}</Foo>
236236
<Bar>{Promise.resolve([dedupedChild])}</Bar>
237237
<Navigate/>
238+
<ClientContextvalue="from server">
239+
<div>
240+
<ClientReadContext/>
241+
</div>
242+
</ClientContext>
238243
{prerender ? null : (// TODO: prerender is broken for large content for some reason.
239244
<React.Suspensefallback={null}>
240245
<LargeContent/>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use client';
2+
3+
import{createContext,use}from'react';
4+
5+
constClientContext=createContext(null);
6+
7+
functionClientReadContext(){
8+
constvalue=use(ClientContext);
9+
return<p>{value}</p>;
10+
}
11+
12+
export{ClientContext,ClientReadContext};

‎packages/react-reconciler/src/ReactFiberBeginWork.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ import {
128128
REACT_LAZY_TYPE,
129129
REACT_FORWARD_REF_TYPE,
130130
REACT_MEMO_TYPE,
131+
REACT_CONTEXT_TYPE,
131132
}from'shared/ReactSymbols';
132133
import{setCurrentFiber}from'./ReactCurrentFiber';
133134
import{
@@ -2140,6 +2141,10 @@ function mountLazyComponent(
21402141
props,
21412142
renderLanes,
21422143
);
2144+
} else if ($$typeof === REACT_CONTEXT_TYPE) {
2145+
workInProgress.tag=ContextProvider;
2146+
workInProgress.type=Component;
2147+
returnupdateContextProvider(null,workInProgress,renderLanes);
21432148
}
21442149
}
21452150

‎packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,44 @@ describe('ReactLazy', () => {
116116
expect(root).toMatchRenderedOutput('Hi again');
117117
});
118118

119+
it('renders a lazy context provider',async()=>{
120+
constContext=React.createContext('default');
121+
functionConsumerText(){
122+
return<Texttext={React.useContext(Context)}/>;
123+
}
124+
// Context.Provider === Context, so we can lazy-load the context itself
125+
constLazyProvider=lazy(()=>fakeImport(Context));
126+
127+
constroot=ReactTestRenderer.create(
128+
<Suspensefallback={<Texttext="Loading..."/>}>
129+
<LazyProvidervalue="Hi">
130+
<ConsumerText/>
131+
</LazyProvider>
132+
</Suspense>,
133+
{
134+
unstable_isConcurrent: true,
135+
},
136+
);
137+
138+
awaitwaitForAll(['Loading...']);
139+
expect(root).not.toMatchRenderedOutput('Hi');
140+
141+
awaitact(()=>resolveFakeImport(Context));
142+
assertLog(['Hi']);
143+
expect(root).toMatchRenderedOutput('Hi');
144+
145+
// Should not suspend on update
146+
root.update(
147+
<Suspensefallback={<Texttext="Loading..."/>}>
148+
<LazyProvidervalue="Hi again">
149+
<ConsumerText/>
150+
</LazyProvider>
151+
</Suspense>,
152+
);
153+
awaitwaitForAll(['Hi again']);
154+
expect(root).toMatchRenderedOutput('Hi again');
155+
});
156+
119157
it('can resolve synchronously without suspending',async()=>{
120158
constLazyText=lazy(()=>({
121159
then(cb){
@@ -858,13 +896,20 @@ describe('ReactLazy', () => {
858896
);
859897
});
860898

861-
it('throws with a useful error when wrapping Context with lazy()',async()=>{
862-
constContext=React.createContext(null);
863-
constBadLazy=lazy(()=>fakeImport(Context));
899+
it('renders a lazy context provider without value prop',async()=>{
900+
// Context providers work when wrapped in lazy()
901+
constContext=React.createContext('default');
902+
constLazyProvider=lazy(()=>fakeImport(Context));
903+
904+
functionConsumerText(){
905+
return<Texttext={React.useContext(Context)}/>;
906+
}
864907

865908
constroot=ReactTestRenderer.create(
866909
<Suspensefallback={<Texttext="Loading..."/>}>
867-
<BadLazy/>
910+
<LazyProvidervalue="provided">
911+
<ConsumerText/>
912+
</LazyProvider>
868913
</Suspense>,
869914
{
870915
unstable_isConcurrent: true,
@@ -873,16 +918,9 @@ describe('ReactLazy', () => {
873918

874919
awaitwaitForAll(['Loading...']);
875920

876-
awaitresolveFakeImport(Context);
877-
root.update(
878-
<Suspensefallback={<Texttext="Loading..."/>}>
879-
<BadLazy/>
880-
</Suspense>,
881-
);
882-
awaitwaitForThrow(
883-
'Element type is invalid. Received a promise that resolves to: Context. '+
884-
'Lazy element type must resolve to a class or function.',
885-
);
921+
awaitact(()=>resolveFakeImport(Context));
922+
assertLog(['provided']);
923+
expect(root).toMatchRenderedOutput('provided');
886924
});
887925

888926
it('throws with a useful error when wrapping Context.Consumer with lazy()',async()=>{

‎packages/react-server-dom-turbopack/src/ReactFlightTurbopackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-unbundled/src/ReactFlightUnbundledReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,10 @@ const deepProxyHandlers: Proxy$traps<mixed> = {
182182
// $FlowFixMe[prop-missing]
183183
returnObject.prototype[Symbol.toStringTag];
184184
case'Provider':
185-
thrownewError(
186-
`Cannot render a Client Context Provider on the Server. `+
187-
`Instead, you can export a Client Component wrapper `+
188-
`that itself renders a Client Context Provider.`,
189-
);
185+
// Context.Provider === Context in React, so return the same reference.
186+
// This allows server components to render <ClientContext.Provider>
187+
// which will be serialized and executed on the client.
188+
returnreceiver;
190189
case'then':
191190
thrownewError(
192191
`Cannot await or return from a thenable. `+

‎packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -787,19 +787,68 @@ describe('ReactFlightDOM', () => {
787787
<ClientModule.Componentkey="this adds instrumentation"/>;
788788
});
789789

790-
it('throws when accessing a Context.Provider below the client exports',()=>{
790+
it('does not throw when accessing a Context.Provider from client exports',()=>{
791791
constContext=React.createContext();
792792
constClientModule=clientExports({
793793
Context,
794794
});
795795
functiondotting(){
796796
returnClientModule.Context.Provider;
797797
}
798-
expect(dotting).toThrowError(
799-
`Cannot render a Client Context Provider on the Server. `+
800-
`Instead, you can export a Client Component wrapper `+
801-
`that itself renders a Client Context Provider.`,
798+
expect(dotting).not.toThrowError();
799+
});
800+
801+
it('can render a client Context.Provider from a server component',async()=>{
802+
// Create a context in a client module
803+
constTestContext=React.createContext('default');
804+
constClientModule=clientExports({
805+
TestContext,
806+
});
807+
808+
// Client component that reads context
809+
functionClientConsumer(){
810+
constvalue=React.useContext(TestContext);
811+
return<span>{value}</span>;
812+
}
813+
const{ClientConsumer: ClientConsumerRef}=clientExports({ClientConsumer});
814+
815+
functionPrint({response}){
816+
returnuse(response);
817+
}
818+
819+
functionApp({response}){
820+
return(
821+
<Suspensefallback={<h1>Loading...</h1>}>
822+
<Printresponse={response}/>
823+
</Suspense>
824+
);
825+
}
826+
827+
// Server component that provides context
828+
functionServerApp(){
829+
return(
830+
<ClientModule.TestContext.Providervalue="from-server">
831+
<div>
832+
<ClientConsumerRef/>
833+
</div>
834+
</ClientModule.TestContext.Provider>
835+
);
836+
}
837+
838+
const{writable, readable}=getTestStream();
839+
const{pipe}=awaitserverAct(()=>
840+
ReactServerDOMServer.renderToPipeableStream(<ServerApp/>,webpackMap),
802841
);
842+
pipe(writable);
843+
constresponse=ReactServerDOMClient.createFromReadableStream(readable);
844+
845+
constcontainer=document.createElement('div');
846+
constroot=ReactDOMClient.createRoot(container);
847+
awaitact(()=>{
848+
root.render(<Appresponse={response}/>);
849+
});
850+
851+
expect(container.innerHTML).toBe('<div><span>from-server</span></div>');
803852
});
804853

805854
it('should progressively reveal server components',async()=>{

‎packages/react-server/src/ReactFlightServerTemporaryReferences.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,10 @@ const proxyHandlers: Proxy$traps<mixed> = {
6565
// $FlowFixMe[prop-missing]
6666
return Object.prototype[Symbol.toStringTag];
6767
case 'Provider':
68-
thrownewError(
69-
`Cannot render a Client Context Provider on the Server. `+
70-
`Instead, you can export a Client Component wrapper `+
71-
`that itself renders a Client Context Provider.`,
72-
);
68+
// Context.Provider === Context in React, so return the same reference.
69+
// This allows server components to render <ClientContext.Provider>
70+
// which will be serialized and executed on the client.
71+
return receiver;
7372
case 'then':
7473
// Allow returning a temporary reference from an async function
7574
// Unlike regular Client References, a Promise would never have been serialized as

0 commit comments

Comments
 (0)