T
TanStack2mo ago
automatic-azure

Route's beforeLoad behaviour

I've been working with TanStack Router, and I want make sure I understand this well. Say, I'm fetching some data in the beforeLoad of a route (eg /dashboard), and this data gets fetched whenever I load the dashboard page or any other page under the /dashboard route. What I want to know is, when moving between different pages under the /dashboard route using Link or navigate, does the data get refetched with each page I visit?
2 Replies
other-emerald
other-emerald2mo ago
actually beforeLoad runs for every navigation for that route and all routes under it, so if you are fetching data in beforeLoad make sure you are using some kind of caching which is handling the refetching issue. usually it's the loader which is recommended for data fetching try to use these config in route definition if you are using loader to fetch data and you also want to avoid refetching // Similar to Remix's default functionality, you may want to configure a route // to only load on entry or when critical loader deps change. // Do not cache this route's data after it's unloaded gcTime: 0, // Only reload the route when the user navigates to it or when deps change shouldReload: false, beforeLoad is kind of like a middleware for a route, so it is supposed to run on every navigation
robust-apricot
robust-apricot2mo ago
Do note: there are obviously some times where you have to do this in the beforeLoad, such as authentication. As long as you are using tanstack query or some similar caching mechanism as @amanmavai said, you will be fine since that becomes instant on subsequent runs

Did you find this page helpful?