DavidKim
DavidKim3y ago

Is it anti pattern to use the useQuery

Is it anti-pattern to use the useQuery hook inside a useEffect hook ?
6 Replies
DavidKim
DavidKimOP3y ago
I'm using nextjs and I have a pattern where I pass an Id of an object to a url query and retrieve it via the router hook. The problem I'm having is that the router hook returns undefined as the query for the first render, which breaks my usage of useQuery unless I wrap it inside a useEffect hook If there's a more suitable pattern to use useQuery based on dyanmic query url, would love help!
Night
Night3y ago
With use Query I usually append || [] (or empty object, or whatever the equivalent for your data type) at the end so that it doesn't throw errors.
lee
lee3y ago
Doing useQuery in a useEffect won't work too well. You can do as @Night suggested to have a default value. Or if there's no convenient default you can conditionally render a subcomponent. Like if (router.query.user) { return <UserProfile user={router.query.user} /> } and inside UserProfile you call useQuery
lee
lee3y ago
And just to give all the options, inside a useEffect you could a single, non-reactive query using ConvexHttpClient https://docs.convex.dev/api/modules/browser
Module: browser | Convex Developer Hub
Tools for accessing Convex in the browser.
Indy
Indy3y ago
Generally calling hooks from inside useEffect is a no go. This is because of how hooks are implemented in React (order of calling them in your react function matters). Nesting hooks like useQuery inside useEffect will likely do very unexpected things. Detailed explanation can be found in the React rules of hooks documentation: https://reactjs.org/docs/hooks-rules.html#explanation
Rules of Hooks – React
A JavaScript library for building user interfaces
DavidKim
DavidKimOP3y ago
Thank you all! The natural workaround I arrived at was pretty much what Varun suggested so I feel less dumb haha

Did you find this page helpful?