Steve A
Steve A6d ago

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);
},
}
);
2 Replies
BeBoRE
BeBoRE6d ago
What does it say in your devtools? If you are using SSR the subscription also runs I believe, don’t know if that’s fixed.
Steve A
Steve AOP19h ago
It seems like it's probably related to SSR, I think you're right. When I move it outside of React into vanilla JS land, there's no issue at all. Thanks, I think that's as good as confirmed for me

Did you find this page helpful?