diff --git a/apps/web/src/hooks/useActiveThreadRef.ts b/apps/web/src/hooks/useActiveThreadRef.ts index e19456e6cb519..13d8bfd780b1d 100644 --- a/apps/web/src/hooks/useActiveThreadRef.ts +++ b/apps/web/src/hooks/useActiveThreadRef.ts @@ -1,6 +1,15 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { useMemo } from "react"; +import { useState } from "react"; + +function toThreadRef( + environmentId: EnvironmentId | null, + threadId: ThreadId | null, +): ScopedThreadRef | null { + return environmentId !== null && threadId !== null + ? scopeThreadRef(environmentId, threadId) + : null; +} /** * Takes the thread object but keys on its ids: the shell changes identity on every update @@ -11,9 +20,11 @@ export function useActiveThreadRef( ): ScopedThreadRef | null { const environmentId = thread?.environmentId ?? null; const threadId = thread?.id ?? null; - return useMemo( - () => - environmentId !== null && threadId !== null ? scopeThreadRef(environmentId, threadId) : null, - [environmentId, threadId], - ); + const [ref, setRef] = useState(() => toThreadRef(environmentId, threadId)); + if ((ref?.environmentId ?? null) !== environmentId || (ref?.threadId ?? null) !== threadId) { + const next = toThreadRef(environmentId, threadId); + setRef(next); + return next; + } + return ref; }