Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/shared-base-ui/src/hooks/useValueRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ function getServerSnapshot(): never {
}
export function useValueRef<T>(ref: ValueRef<T>): T {
if ('readyPromise' in ref) {
const ref2 = ref as ValueRefWithReady<T>
if (!ref2.ready) use(ref2.readyPromise)
// Must NOT be conditional on `ref.ready`. When a component suspends here and is replayed
// after the promise resolves, React only switches from the update dispatcher back to the
// mount dispatcher inside `use`. Skipping `use` on replay (because `ready` flipped to true)
// makes the following hooks throw "Update hook called on initial render" (React #467).
// `use` on an already-resolved promise returns synchronously once React has tracked it.
use((ref as ValueRefWithReady<T>).readyPromise)
}
return useSyncExternalStore(
(f) => ref.addListener(f),
Expand Down
5 changes: 4 additions & 1 deletion packages/shared-base/src/helpers/ValueRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ export class ValueRefWithReady<T> extends ValueRef<T> {
// this is unsafe. we assigned T | undefined to T
super(value!, isEqual)
const { promise, resolve } = Promise.withResolvers<void>()
this.readyPromise = promise.then(() => this.value)
const readyPromise = promise.then(() => this.value)
// Follow React's thenable protocol so `use(readyPromise)` returns synchronously once ready.
readyPromise.then((value) => Object.assign(readyPromise, { status: 'fulfilled', value }))
this.readyPromise = readyPromise
this.#nowReady = resolve
}

Expand Down
Loading