T
TanStack3w ago
probable-pink

How to Dynamically Update the Page Title After Rendering

How can I dynamically update the <title> tag after the page has been rendered? I am currently using the following code to render the title for pages:
head: ({ loaderData }) => {
const meta: AnyRouteMatch["meta"] = [];
if (loaderData?.title) {
meta.push({ title: titleTag(loaderData.title) });
}
return {
meta,
};
},
head: ({ loaderData }) => {
const meta: AnyRouteMatch["meta"] = [];
if (loaderData?.title) {
meta.push({ title: titleTag(loaderData.title) });
}
return {
meta,
};
},
In my app, there is a use case where I receive the title from WebSocket messages. I tried updating the title with document.title = event.data.title, but the problem is that when I navigate to the home page (client side), the dynamically set title still shows and does not update correctly.
1 Reply
probable-pink
probable-pinkOP3w ago
I came to know in React 19, we can use the title element. This approched fixed my problem.
function RouteComponent() {
const { conversationID } = Route.useParams();
const { data: conversation } = useSuspenseQuery(
messagesQueryOptions(conversationID),
);
const title = useConversationStore().conversation[conversation.id]?.title;
return (
<>
{title && <title>{title}</title>}
<Conversation messages={conversation.messages} />
</>
);
}
function RouteComponent() {
const { conversationID } = Route.useParams();
const { data: conversation } = useSuspenseQuery(
messagesQueryOptions(conversationID),
);
const title = useConversationStore().conversation[conversation.id]?.title;
return (
<>
{title && <title>{title}</title>}
<Conversation messages={conversation.messages} />
</>
);
}

Did you find this page helpful?