Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

shared-singleton.tsx

55 lines1.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import * as React from 'react'
3​
4// All shared state lives in declarations β€” no bare expression statements.
5// The singleton tracks how many times this module scope executes.
6const singleton = (() => {
7 const g = globalThis as any
8 g.__tsrSharedSingleton ??= { initCount: 0 }
9 g.__tsrSharedSingleton.initCount++
10 return { initCountAtCreate: g.__tsrSharedSingleton.initCount as number }
11})()
12​
13function getInitCount() {
14 return (globalThis as any).__tsrSharedSingleton?.initCount as number
16​
17export const Route = createFileRoute('/shared-singleton')({
18 loader: () => {
19 return {
20 loaderSawInitCount: getInitCount(),
21 initCountAtCreateFromLoader: singleton.initCountAtCreate,
22 }
23 },
24 component: SharedSingletonComponent,
25})
26​
27function SharedSingletonComponent() {
28 const data = Route.useLoaderData()
29​
30 return (
31 <div className="p-2 space-y-2">
32 <h3 className="text-lg font-bold">Shared Singleton</h3>
33 <div>
34 initCount (global):{' '}
35 <span data-testid="shared-init-count">{getInitCount()}</span>
36 </div>
37 <div>
38 loaderSawInitCount:{' '}
39 <span data-testid="shared-loader-saw">{data.loaderSawInitCount}</span>
40 </div>
41 <div>
42 initCountAtCreate (loader module):{' '}
43 <span data-testid="shared-created-at-loader">
44 {data.initCountAtCreateFromLoader}
45 </span>
46 </div>
47 <div>
48 initCountAtCreate (component module):{' '}
49 <span data-testid="shared-created-at-module">
50 {singleton.initCountAtCreate}
51 </span>
52 </div>
53 </div>
54 )