Shiladitya Thakur
Shiladitya Thakur

Reputation: 330

is it possible to cache data from server side with react-query and nextjs?

I am new to react-query and my webapp uses nextjs with firebase. I have few pages (projects.jsx and [id],jsx) that solely depend on prefetched data from server side. However, they are fetching data from exactly the same api route.

I was hoping using react query within getStaticProps would cache the results and from there I can send the data onto client side. But from what all I tried, it seems the caching happens on client side only like when I call

useQuery("projects", () => fetch("/projects"), {
  initialData: projects //assume projects contains all the projects from getStaticProps()
})

But doing so defeats the purpose of minimizing async calls to firebase from server side. So, is there a way to achieve caching in server side or is getStaticProps() the only option?

Upvotes: 0

Views: 1702

Answers (1)

TkDodo
TkDodo

Reputation: 28803

I think your approach with initialData should work, and is also outlined in the docs. Further, in this section of the docs, it states that:

Because staleTime defaults to 0, queries will be refetched in the background on page load by default. You might want to use a higher staleTime to avoid this double fetching, especially if you don't cache your markup.

And I guess this is what is happening for you. To prevent that, setting a higher staleTime is likely what you want. If you provide initialData with staleTime: Infinity, the data will not be refetched at all (unless the query is garbage collected).

Upvotes: 1

Related Questions