rsnext/packages/next/shared/lib/flush-effects.ts
Gerald Monaco 944c734d04
Add unstable_useFlushEffects hook (#34117)
Implements https://github.com/vercel/next.js/issues/30997 with some minor tweaks to the design:

* The hook is moved to Client Components (e.g. `pages/_app` instead of `pages/_document`). This was a silly oversight in the original design: the hook needs to be called during server prerendering.

* `useFlushEffects` instead of `useFlushEffect` as there isn't a particularly safe way to implement the singular semantics as a Client Component hook given the current implementation of server rendering.

---

Fixes #30997
2022-02-18 00:18:28 +00:00

21 lines
717 B
TypeScript

import { createContext, useContext } from 'react'
export type FlushEffectsHook = (callbacks: Array<() => React.ReactNode>) => void
export const FlushEffectsContext: React.Context<FlushEffectsHook | null> =
createContext(null as any)
export function useFlushEffects(callbacks: Array<() => React.ReactNode>): void {
const flushEffectsImpl = useContext(FlushEffectsContext)
if (!flushEffectsImpl) {
throw new Error(
`useFlushEffects can not be called on the client.` +
`\nRead more: https://nextjs.org/docs/messages/client-flush-effects`
)
}
return flushEffectsImpl(callbacks)
}
if (process.env.NODE_ENV !== 'production') {
FlushEffectsContext.displayName = 'FlushEffectsContext'
}