Convex + Nextjs using preloadQuery inside layout.tsx
Hi,
I am trying to understand if doing a preloadQuery inside a layout.tsx and share it amongst my "use client" pages through a "react context" has any advantages over using useQuery on each page (assuming the data hasn't changed). Or if it's an anti-pattern cause layout.tsx is loaded once and will not cause re-renders?
6 Replies
Thanks for posting in <#1088161997662724167>.
Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets.
- Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.)
- Use search.convex.dev to search Docs, Stack, and Discord all at once.
- Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI.
- Avoid tagging staff unless specifically instructed.
Thank you!
I assume it helps with first page load speed due to the page content being fully cacheable by cdn / edge
Or if it's an anti-pattern cause layout.tsx is loaded once and will not cause re-renders?What you described, using preloadQuery and sharing it, becomes a live query after hydration. The only reason it could be an anti-pattern is that it's less composeable, the component with the useQuery in it needs to be passed this data from a server component. The advantage is like Heath says above, the useQuery wil l never be in a loading state
Interesting, so the sharing part (using a context) is a "code smell" if I get you correctly. But it will give advantage if I aim to avoid loading, sorry for repeating your answers I just want to make sure I got it right hehe. I now also wonder what will happen if the data changes, have I caused re-renders to all pages (even those that doesn't need the query) using the layout? (I guess I can test that one myself fast as this is also not a convex specific question)
Only the useQuery() that uses the preloaded data will rerender, like a normal useQuery() hook. The context sounds fine to me, no code smells in my opinion.
Thanks