Steve A
Steve A
TtRPC
Created by Steve A on 3/21/2025 in #❓-help
Doubled subscriptions in React with useSubscription
I've searched a bit but can't seem to find an answer: When using useSubscription, I seem to get two subscriptions due to React strict mode. Is there a way to prevent this? I don't see an API for disposing of subscriptions when the component unmounts, so subscriptions only accumulate. But perhaps I'm doing something obviously wrong that I'm not catching? Here is the gist of the code I'm using:
function ChatIndexComponent() {
const chatId = Route.useParams({ select: (d) => d.chatId });
const { send } = useChatActorRef();
const chatQuery = trpc.chatWithMessages.useQuery(chatId);
const chat = chatQuery.data;

// This seems to run twice, but the subscription isn't disposed of when the component unmounts
trpc.messageStream.useSubscription(
{
chatId,
},
{
enabled: true,
onData: ({ data }) => {
send(data);
},
}
);
function ChatIndexComponent() {
const chatId = Route.useParams({ select: (d) => d.chatId });
const { send } = useChatActorRef();
const chatQuery = trpc.chatWithMessages.useQuery(chatId);
const chat = chatQuery.data;

// This seems to run twice, but the subscription isn't disposed of when the component unmounts
trpc.messageStream.useSubscription(
{
chatId,
},
{
enabled: true,
onData: ({ data }) => {
send(data);
},
}
);
3 replies