Question: How to Use useQuery with Suspense in Next.js App Router for Client-Side Only Fetching? #7596
-
I am using Next.js with the App Router and tanstack-query for data fetching. I have set the suspense option to true for useQuery. However, this causes fetch to run on the server side first and then again on the client side. For user-based requests, I want to ensure that network requests via useQuery occur only on the client side. Additionally, I want to avoid unnecessary server-side requests while using Suspense for loading states. I have tried setting the enabled option to typeof window !== 'undefined', but it still results in the fetch being executed on the server side first, followed by another network request on the client side. I have referred to this discussion which addresses a similar issue, but I am still unsure of the best approach to handle this scenario. Is there a best practice to achieve this without removing Suspense or manually handling loading states, and without intentionally switching to client-side rendering? Any guidance or recommendations would be greatly appreciated. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
suspense running on the server is a feature in next js. You can try to have a hook that uses suspense on the client only and not on the server, but honestly, this kinda defeats the purpose of using suspense (it's meant for the server first and foremost):
|
Beta Was this translation helpful? Give feedback.
-
Another solution is to render the component only on client side, like this: const NoSsr = ({ children }) => {
const [isClient, setClient] = useState(false)
useEffect(() => {
setClient(true)
}, [])
return isClient ? children : null
}
const MyComponent = () => {
const { ... } = useSuspenseQuery({ ... })
return (...)
}
export default () => {
return (
<NoSsr>
<MyComponent />
</NoSsr>
)
} You can use Next.js' |
Beta Was this translation helpful? Give feedback.
suspense running on the server is a feature in next js. You can try to have a hook that uses suspense on the client only and not on the server, but honestly, this kinda defeats the purpose of using suspense (it's meant for the server first and foremost):