Unverified Commit aef60dc5 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Support multiple flush effects (#39559)

Bring more flexibility for consume flush effects in separate places. Then you can move it into different client components roots
parent 2b2c2acf
......@@ -1018,23 +1018,19 @@ export async function renderToHTMLOrFlight(
}
)
let flushEffectsHandler: (() => React.ReactNode) | null = null
const flushEffectsCallbacks: Set<() => React.ReactNode> = new Set()
function FlushEffects({ children }: { children: JSX.Element }) {
// Reset flushEffectsHandler on each render
flushEffectsHandler = null
const setFlushEffectsHandler = React.useCallback(
flushEffectsCallbacks.clear()
const addFlushEffects = React.useCallback(
(handler: () => React.ReactNode) => {
if (flushEffectsHandler)
throw new Error(
'The `useFlushEffects` hook cannot be used more than once.'
)
flushEffectsHandler = handler
flushEffectsCallbacks.add(handler)
},
[]
)
return (
<FlushEffectsContext.Provider value={setFlushEffectsHandler}>
<FlushEffectsContext.Provider value={addFlushEffects}>
{children}
</FlushEffectsContext.Provider>
)
......@@ -1063,7 +1059,7 @@ export async function renderToHTMLOrFlight(
const flushEffectHandler = (): string => {
const flushed = ReactDOMServer.renderToString(
<>{flushEffectsHandler && flushEffectsHandler()}</>
<>{Array.from(flushEffectsCallbacks).map((callback) => callback())}</>
)
return flushed
}
......
......@@ -6,9 +6,10 @@ export const FlushEffectsContext = createContext<FlushEffectsHook | null>(
null as any
)
export function useFlushEffects(callbacks: () => React.ReactNode): void {
const flushEffectsImpl = useContext(FlushEffectsContext)
export function useFlushEffects(callback: () => React.ReactNode): void {
const addFlushEffects = useContext(FlushEffectsContext)
// Should have no effects on client where there's no flush effects provider
if (!flushEffectsImpl) return
return flushEffectsImpl(callbacks)
if (addFlushEffects) {
addFlushEffects(callback)
}
}
......@@ -19,13 +19,13 @@ export default function RootStyleRegistry({ children }) {
return <>{styles}</>
}
// Allow multiple useFlushEffects
useFlushEffects(() => {
return (
<>
{styledJsxFlushEffect()}
{styledComponentsFlushEffect()}
</>
)
return <>{styledJsxFlushEffect()}</>
})
useFlushEffects(() => {
return <>{styledComponentsFlushEffect()}</>
})
// Only include style registry on server side for SSR
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment