TanStackT
TanStack12mo ago
3 replies
abstract-purple

Using global variable store in @tanstack/start dangerous? or just acceptable in @tanstack/router?

I'm looking at the tanstack/router examples for data loading, and I will see this pattern
//https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading
//THIS IS A GLOBAL VARIABLE
let postsCache = []

export const Route = createFileRoute('/posts')({
  loader: async () => {
    postsCache = await fetchPosts()
  },
  component: () => {
    return (
      <div>
        {postsCache.map((post) => (
          <Post key={post.id} post={post} />
        ))}
      </div>
    )
  },
})


Or

//From basic-react-query example in @tanstack/router
//THIS IS A GLOBAL VARIABLE
const queryClient = new QueryClient()

// Set up a Router instance
const router = createRouter({
  routeTree,
  defaultPreload: 'intent',
  // Since we're using React Query, we don't want loader calls to ever be stale
  // This will ensure that the loader is always called when the route is preloaded or visited
  defaultPreloadStaleTime: 0,
  scrollRestoration: true,
  context: {
    queryClient,
  },
})

I understand that @tanstack/router it is 100% on the client, so this should be fine. But can I use this pattern in @tanstack/start as well? Since it will be run on the server, will these global variables LEAK if they are run for different authenticated users for example? Or is tanstacks/start implementation that these are run inside some closure?

In @tanstack/start
export function createRouter() {
//Inside Closure
  const queryClient = new QueryClient()

  return routerWithQueryClient(
    createTanStackRouter({
      routeTree,
      context: { queryClient },
      defaultPreload: 'intent',
      defaultErrorComponent: DefaultCatchBoundary,
      defaultNotFoundComponent: () => <NotFound />,
    }),
    queryClient,
  )
}
Was this page helpful?