How does the query cache work on Next.JS?
This is probably one of the easiest questions lol, but at work we were talking about react query and how it caches fetched data. We couldn't really find an answer on how caching works between pages (on app router) - like, in this scenario:
i'm assuming
ClientComponent2 will fetch the same data from cache that was originally fetched and set from ClientComponent1, right?
(it's been a little bit since i've used react-query in a large app (last time was in a vite app) so these details are a little hazy to me in the moment)
and a follow up - how could we use that same cached data in either page.tsx? since it's server rendered6 Replies
fair-rose•11mo ago
Caching in react query is simply an object in memory. As long as you don't refresh the page (or close and reopen) then caching will work. In your example, yes both components mount the same
queryKey, and so as long as the data in cache is not stale, the queryFn son't be re-executed.
As for SSR, I never tried it so i couldn't say.eastern-cyanOP•11mo ago
yeah, what we're trying to think through is
- on page-1 we are fetching and displaying some search results
- you click a link on page-1 to go to page-2, page-2 opens a new tab
- on page-2 theres a back link
- you click the back link, and you're redirected to page-1
- we want to persist the search results from the first visit
- if you just refresh page-1, you'd get a new set of results
page-1 fetches new results on each page load (depends on a backend algo to get the "best" results, which can change / give a different set of results at any point in time due to other factors), so we wanted to save those results since clicking back is most likely going to happen within the same block of time where we probably don't care as much about fetching a new set of results again
i think our better solution is using redis here so we can intercept the results before the page is rendered, but our talk about react-query got me thinking this could also work 😛
fair-rose•11mo ago
Yeah react query isn't going to help for this, it seems like you'd need to store the results somewhere (redis or even locally like localStorage)
sensitive-blue•11mo ago
if you want the cache to sync between tabs, I'd suggest looking into one of the persister plugins that write to e.g. localstorage, so that the second tab can pick these things up.
fascinating-indigo•11mo ago
Hello, there.
I have a problem on my react project.
can you help me?
Please let me know.
fair-rose•11mo ago
@Dream you should ask your question in #query or #react-query-questions