I have a Next.js application where I use @tanstack/react-query@4 for state management and data fetching. I use it for authentication state via a custom useUser() hook that is used throughout the app, including in a nav bar component shared across all pages in a layout component. Let's say I have two identical pages showing me the current user. When I first open my app, everything works fine as the data is shared between the page and the nav bar. Whether I enter page A or B, the observer count for the key ["user"] is 2. The weird thing is that when I navigate to another page and refetch the key, it seems to detach the key from the nav bar, and it stays un-updated (you can see that the observer count is 1). Any advice on how to keep those linked will help!
The problem is you're having an "unstable" QueryClient, as you just create it inside the App
component:
export default function App({ Component, pageProps }: AppProps) {
const queryClient = new QueryClient()
so every time App
re-renders, you'll get a new QueryClient. The QueryClient holds the QueryCache, so you throw away cached data, and attached observers etc.
The solution is to keep the client stable, either by moving the instantiation out of the App
component, or by putting it into state or an instance ref. For a nextJs application, moving it out of the component is not recommended because it means data might be shared between users when server-rendering. So, as in the docs, this is the solution:
export default function App({ Component, pageProps }: AppProps) {
const [queryClient] = useState(() => new QueryClient());