#convex useQuery in child components
3 messages · Page 1 of 1 (latest)
Your question is about using Convex's useQuery and usePreloadedQuery hooks in React components, which is a topic covered in the provided knowledge sources. Let me address your specific scenario.
The approach you're using to combine server-side data fetching with client-side updates is generally on the right track, but there are a few optimizations and best practices we can consider:
-
Using
preloadQueryandusePreloadedQuery:
Your use ofpreloadQueryfor server-side data fetching andusePreloadedQueryfor client-side hydration is correct. This approach helps with initial page load performance and SEO, as described in the Next.js Server Rendering (https://docs.convex.dev/client/react/nextjs/server-rendering) documentation. -
Combining
useQueryandusePreloadedQuery:
While it's possible to use both hooks as you've done, it's generally not necessary. TheusePreloadedQueryhook is designed to seamlessly transition from server-rendered data to live, reactive data. As mentioned in the documentation:
usePreloadedQuery` takes three arguments:
1. The query reference
2. Optionally the arguments object passed to the query
3. Optionally a **NextjsOptions** (<https://docs.convex.dev/api/modules/nextjs#nextjsoptions>) object
Next.js Server Rendering (https://docs.convex.dev/client/react/nextjs/server-rendering)
Instead of using both hooks, you could simplify your code to just use usePreloadedQuery:
const columnData = usePreloadedQuery(initialColumns);
const [columns, setColumns] = useState<ColumnData>(columnData || DEFAULT_COLUMNS);
This way, you'll get the initial server-rendered data, and it will automatically update when changes occur on the server.
-
Avoiding unnecessary state:
With Convex's reactive queries, you often don't need to manage state for query results manually. TheusePreloadedQueryhook will automatically update when data changes, so you might not need theuseStateanduseEffectcombination you're currently using. -
Consistency:
Be aware that when using multiplepreloadQuerycalls, you might encounter consistency issues as mentioned in the Consistency (https://docs.convex.dev/client/react/nextjs/server-rendering#consistency) section of the documentation. It's best to avoid using multiplepreloadQuerycalls on the same page if possible.
To answer your final question: Yes, the way you're getting the preloaded data and showing it is generally correct, but it can be simplified. The usePreloadedQuery hook is designed to handle both the initial server-rendered data and subsequent live updates, so you don't need to combine it with a separate useQuery call for the same data.