How to get referential equality for query result when switching pages with Next.js #4242
-
When using the same query on two pages in Next.js, switching from one page to the other will "lose" the referential equality of the returned data. Imagine fetching a user on one page. When going to another page that uses the exact same query, when using the returned data e.g. in a Here's a basic example: export default function SomePage() {
const { data } = useQuery(
["some-id"],
async () => (await fetchData("some-id")).result ?? null,
{ refetchOnMount: false, cacheTime: Infinity }
);
useEffect(() => {
console.log("query has changed data");
}, [data]);
return (
<div>
<p>data</p>
<p>{data?.blabla}</p>
</div>
);
} You can create two pages in Next.js to see that the effect is triggered, even though the data is structurally equal. Is this expected? If yes, maybe one should use the new Btw, maybe it has something to do with the query client, I initialize it like this: // _app.tsx
function App({ Component, pageProps }: AppProps): JSX.Element {
const [queryClient] = useState(() => new QueryClient());
return (
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
... |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
The code you are showing looks fine. Is getServerSideProps involved by any chance? It's best to just show a codesandbox reproduction please. |
Beta Was this translation helpful? Give feedback.
The code you are showing looks fine. Is getServerSideProps involved by any chance? It's best to just show a codesandbox reproduction please.