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

structural-sharing.$enabled.tsx

80 lines2.0 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { Link, getRouteApi, useSearch } from '@tanstack/react-router'
3import React from 'react'
4import { z } from 'zod'
5​
6const enabledSchema = {
7 enabled: z.preprocess((val) => {
8 if (typeof val === 'string') {
9 if (val.toLowerCase() === 'true') return true
10 if (val.toLowerCase() === 'false') return false
11 }
12 return val
13 }, z.boolean()),
15​
16export const Route = createFileRoute('/structural-sharing/$enabled')({
17 component: RouteComponent,
18 params: {
19 parse: (p) => z.object(enabledSchema).parse(p),
20 },
21 validateSearch: z.object({ foo: z.string(), bar: z.string() }),
22})
23​
24function useRenderCount() {
25 const count = React.useRef(0)
26 count.current++
27 return count.current
29​
30const api = getRouteApi('/structural-sharing/$enabled')
31function RouteComponent() {
32 console.log('rendering')
33 const renderCount = useRenderCount()
34 const { enabled } = Route.useParams()
35​
36 const searchViaRouteHook = Route.useSearch({
37 select: ({ foo, bar }) => {
38 return { values: [foo, bar] }
39 },
40 structuralSharing: enabled,
41 })
42​
43 const searchViaHook = useSearch({
44 from: Route.id,
45 select: ({ foo, bar }) => {
46 return { values: [foo, bar] }
47 },
48 structuralSharing: enabled,
49 })
50​
51 const searchViaRouteApiHook = api.useSearch({
52 select: ({ foo, bar }) => {
53 return { values: [foo, bar] }
54 },
55 structuralSharing: enabled,
56 })
57​
58 return (
59 <>
60 <div data-testid="enabled">{JSON.stringify(enabled)}</div>
61 <div data-testid="render-count">{renderCount}</div>
62 <div data-testid="search-via-hook">{JSON.stringify(searchViaHook)}</div>
63 <div data-testid="search-via-route-hook">
64 {JSON.stringify(searchViaRouteHook)}
65 </div>
66 <div data-testid="search-via-route-api-hook">
67 {JSON.stringify(searchViaRouteApiHook)}
68 </div>
69​
70 <br />
71 <Link
72 search={{ foo: 'f2', bar: 'b2' }}
73 from="/structural-sharing/$enabled"
74 data-testid="link"
75 >
76 go to f2/b2
77 </Link>
78 </>
79 )