How to use React Query data in a layout component?
Hey! I have a Next.js application where I use @tanstack/react-query 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!
See in CodeSandbox: https://codesandbox.io/p/sandbox/boring-tristan-xgdhwm
boring-tristan-xgdhwm
CodeSandbox is an online editor tailored for web applications.

0 Replies