<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ytaisei on Medium]]></title>
        <description><![CDATA[Stories by ytaisei on Medium]]></description>
        <link>https://medium.com/@yasui-edu0834?source=rss-954826194748------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Iv4odYS2vjUsvCxuhHk-cA.jpeg</url>
            <title>Stories by ytaisei on Medium</title>
            <link>https://medium.com/@yasui-edu0834?source=rss-954826194748------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:39:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasui-edu0834/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TanStack Router is one of the most powerful options for SPA development(& TanStack Query)]]></title>
            <link>https://medium.com/@yasui-edu0834/tanstack-router-is-one-of-the-most-powerful-options-for-spa-development-tanstack-query-cc7ecdc73550?source=rss-954826194748------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7ecdc73550</guid>
            <category><![CDATA[tanstack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tan-stack-router]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <dc:creator><![CDATA[ytaisei]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 13:47:23 GMT</pubDate>
            <atom:updated>2024-02-18T14:00:12.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fokPKO44BMbbV5bVqY1HTg.jpeg" /></figure><p>For React, <strong>routing and data fetching play particularly important roles.</strong></p><p>Of course, by adopting frameworks like Next.js or Remix, it is possible to implement everything from routing to data fetching using the APIs provided by the framework without adding individual libraries.</p><p>However, for BtoB services, an SPA is often sufficient, and the adoption of frameworks such as Next.js might be unnecessarily excessive.</p><p><strong>What we are seeking is type-safe, file-based routing and efficient data fetching.</strong></p><p>This article introduces, as of February 2024, that TanStack Router is a very strong option as a routing library for SPAs in technology selection.</p><h3>Introduction</h3><p>In this article, I will discuss how the TanStack Router and TanStack Query can be one of the best solutions for SPA applications, based on their features and actual design structure examples.</p><p>Although TanStack Router provides SSR (Server-Side Rendering) capabilities, I will specifically focus on its application in SPAs for this discussion.</p><h4>Target</h4><ul><li>Developers who are considering technology selection for SPAs with React</li><li>Developers who are seeking a type-safe development experience</li><li>Developers who are feeling that adopting frameworks like Next.js is too much</li><li>Developers who are looking for libraries compatible with React + Vite</li></ul><h3>About TanStack Router</h3><p>TanStack Router is a <strong>relatively new library</strong> that was released as version 1.0 on Christmas of 2023. The video posted in this Tweet explains its features in an easy-to-understand, so please take a moment to watch it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/tannerlinsley/status/1738709130213560497%3Fs%3D20&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/c800c28cdf97fc050ef9003469779b63/href">https://medium.com/media/c800c28cdf97fc050ef9003469779b63/href</a></iframe><h3>Type-safe and simple routing</h3><p>One of the major features of TanStack Router is <strong>type safety</strong>.It provides code completion when navigating using &lt;Link /&gt; or useNavigate. Not only does it complete paths, but it also allows for handling path params and search params in a type-safe, which is very powerful.</p><p>Furthermore, the API is very simple and understandable, which is one of the reasons why I feel it offers a high-quality development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JdXNcU_oldH_BlIQhZeNPQ.gif" /><figcaption>TanStack Router Type Safe Example</figcaption></figure><p><a href="https://tanstack.com/router/latest/docs/framework/react/guide/type-safety">Type Safety | TanStack Router Docs</a></p><h3>File-Based Route Generation</h3><p>What I particularly appreciate about TanStack Router is its <strong>file-based routing and its automatic generation</strong>.This means you can define routing through files, similar to the App Router in Next.js or Remix, eliminating the need to implement routing in the codebase.</p><p>Of course, it’s still possible to implement routing based on code, but the official recommendation is towards file-based routing.</p><p>Note: This article introduces routing in the form of Directory Routes, not Flat Routes.</p><p><a href="https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing">File-Based Routes | TanStack Router Docs</a></p><pre>__root.tsx // The root file is applied to all routes.<br>posts/<br>  route.tsx // `/posts`<br>  $postId/<br>    route.tsx // `/posts/$postId`</pre><p>For example, with a directory structure like the above, routes for /posts and /posts/$postId are generated. Additionally, TanStack Router has its own unique file definitions, so I&#39;ll focus on introducing the particularly important ones.</p><h4>File Names with Special Roles</h4><p><strong>__root.tsx</strong></p><p>This is a file that applies to all routes. It does not have a specific path, and the components defined here are always rendered.</p><pre>import { createRootRoute } from &#39;@tanstack/react-router&#39;<br><br>export const Route = createRootRoute()</pre><p>Additionally, by using createRootRouteWithContextAPI instead of createRootRoute, it&#39;s possible to perform Dependency Injection.</p><pre>import { createRootRouteWithContext, createRouter } from &#39;@tanstack/react-router&#39;<br><br>interface MyRouterContext {<br>  queryClient: QueryClient<br>}<br><br>const rootRoute = createRootRouteWithContext&lt;MyRouterContext&gt;()({<br>  component: App,<br>})<br><br>const queryClient = new QueryClient()<br><br>const router = createRouter({<br>  routeTree: rootRoute,<br>  context: {<br>    queryClient,<br>  },<br>})</pre><p><a href="https://tanstack.com/router/v1/docs/framework/react/guide/file-based-routing#file-naming-conventions">File-Based Routes | TanStack Router Docs</a></p><p><strong>$token（ex. $postId）</strong></p><p>Using $ as a prefix means it will be used as a URL pathname. Also, the matched path params can be referenced within loader functions or components.</p><pre>import { createFileRoute } from &#39;@tanstack/react-router&#39;<br><br>export const Route = createFileRoute(&#39;/posts/$postId&#39;)({<br>  loader: async ({ params }) =&gt; {<br>    return fetchPost(params.postId)<br>  },<br>})</pre><p><a href="https://tanstack.com/router/v1/docs/framework/react/guide/path-params">Path Params | TanStack Router Docs</a></p><p><strong>_ prefix</strong></p><p>When using _ as a prefix, it is used as a layout route and is not reflected in the URL pathname. This means the directory structure and routing would correspond as follows.</p><pre>_layout/<br>  layout-a.tsx // → /layout-a<br>  layout-b.tsx // → /layout-b</pre><p>This allows for <strong>the cohesion of closely related routes.</strong></p><h4>RouteOptions type</h4><pre>// routes/posts.tsx<br>export const Route = createFileRoute(&#39;/posts&#39;)({<br>  component, // skip<br>  loader,<br>  errorComponent,<br>  pendingComponent,<br>  validateSearch,<br>})</pre><p><a href="https://tanstack.com/router/v1/docs/framework/react/api/router/RouteOptionsType">RouteOptions type | TanStack Router Docs</a></p><p><strong>loader</strong></p><pre>type loader = ({/** Omitted */}) =&gt; Promise&lt;TLoaderData&gt; | TLoaderData | void</pre><p>This is a feature similar to the loaders in Remix/React-Router. It triggers when the route is called and throws an error if it fails.</p><p>When the loader returns a Promise, the route will be a pending state, and rendering is suspended until the Promise is resolved. If the Promise is rejected, the route will be an error state.</p><p><a href="https://tanstack.com/router/v1/docs/framework/react/guide/data-loading">Data Loading | TanStack Router Docs</a></p><p><strong>errorComponent, </strong><strong>pendingComponent</strong></p><p>In the context of the loader function mentioned above, I explained how rendering can be suspended or will be an error state based on the state of the Promise. Therefore, TanStack Router allows you to define components for each route for error and pending states.</p><pre>// routes/posts.tsx<br>export const Route = createFileRoute(&#39;/posts&#39;)({<br>  component, // success<br>  errorComponent, // error<br>  pendingComponent, // pending<br>})</pre><p><strong>validateSearch</strong></p><p>By using validateSearch, you can validate search params and handle them in a type-safe. Furthermore, it&#39;s possible to combine it with a validation library like zod.</p><pre>import { z } from &#39;zod&#39;<br><br>const productSearchSchema = z.object({<br>  page: z.number().catch(1),<br>  filter: z.string().catch(&#39;&#39;),<br>  sort: z.enum([&#39;newest&#39;, &#39;oldest&#39;, &#39;price&#39;]).catch(&#39;newest&#39;),<br>})<br><br>type ProductSearch = z.infer&lt;typeof productSearchSchema&gt;<br><br>export const Route = createFileRoute(&#39;/shop/products&#39;)({<br>  validateSearch: (search) =&gt; productSearchSchema.parse(search),<br>})</pre><h3>Code Splitting to Reduce Bundle Size</h3><p>TanStack Router comes with built-in functionality for code splitting. There are three main purposes for code splitting (or lazy loading):</p><ol><li><strong>To reduce the amount of code needed for the initial page load.</strong></li><li><strong>To load the targeted code only when it’s needed.</strong></li><li><strong>To enable caching at a more granular level by dividing the code into chunks.</strong></li></ol><h4>How to use Code Splitting</h4><p>The method for code splitting with TanStack Router is straightforward:</p><blockquote><strong>Add the </strong><strong>.lazy.tsx suffix to the file name and use </strong><strong>createLazyFileRoute.</strong></blockquote><p>This enables the distinction between Critical Routes and Lazy Routes.</p><p><strong>Critical Route</strong></p><ul><li>Code that is loaded initially.</li></ul><p><strong>Lazy Route</strong></p><ul><li>Code that is loaded on demand, with a delay.</li></ul><p>So, what criteria should be used to select targets for code splitting?</p><p>it was clarified in the TanStack Router documentation.</p><p><strong>Target for Critical Route（route.tsx）</strong></p><ul><li>Path Parsing/Serialization</li><li>Search Param Validation</li><li>Loaders, Before Load</li><li>Route Context</li><li>Meta</li><li>Links</li><li>Scripts</li><li>Styles</li><li>All other route configuration not listed below</li></ul><p><strong>Target for Lazy Route（route.lazy.tsx）</strong></p><ul><li>Route Component</li><li>Error Component</li><li>Pending Component</li><li>Not-found Component</li></ul><p><strong>Components associated with each route can be designated for Lazy Loading.</strong></p><h4>Loaders are not targeted for code splitting???</h4><p>There are three reasons for not making loaders part of Lazy Routes:</p><ol><li>Targeting loaders would require<strong> two round trips</strong>: one to fetch the chunk for the loader itself and another to execute it.</li><li>Loaders typically have a <strong>relatively small amount of code</strong>, so including them doesn’t significantly contribute to reducing the bundle size.</li><li>For a route, loaders are <strong>crucial elements for preloading</strong>.</li></ol><p><a href="https://tanstack.com/router/v1/docs/framework/react/guide/code-splitting">Code Splitting | TanStack Router Docs</a></p><h3>State Management with Search Params</h3><p>TanStack Router considers search params as a global state and offers features to manage them securely with type safety and validation capabilities.</p><p>For users, the expectation is that the state remains consistent in scenarios such as:</p><ul><li>Opening a new tab via Cmd/Ctrl + Click</li><li>Sharing bookmarks or links</li><li>Refreshing the page</li></ul><p>For developers, this approach to managing search params as flexibly, securely, and with validation as with other state management solutions makes handling search params more efficient.</p><h4>Why not use URLSearchParams?</h4><p>URLSearchParams comes with the following drawbacks:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams">URLSearchParams - Web APIs | MDN</a></p><ol><li>It is always of the <strong>string type</strong>.</li><li>In most cases, it has a <strong>flat structure</strong>.</li><li>When updating search params, it is necessary to <strong>consider the URL pathname</strong>.</li></ol><p>However, when considering search params as a global state, these drawbacks become significant challenges.</p><p>The ideal solution is as follows:</p><ul><li>To handle a variety of types similar to state management libraries, including the ability to <strong>manipulate complex data types</strong> such as nested arrays and objects.</li><li>To manage search params without having to interact with the URL’s pathname.</li></ul><p><strong>TanStack Router addresses these challenges.</strong></p><h4>JSON-first Search Params</h4><p>TanStack Router has a powerful parser that automatically converts search params into structured JSON. This means you can use data that is serializable in JSON as search params.</p><pre>const link = (<br>  &lt;Link<br>    to=&quot;/shop&quot;<br>    search={{<br>      pageIndex: 3,<br>      includeCategories: [&#39;electronics&#39;, &#39;gifts&#39;],<br>      sortBy: &#39;price&#39;,<br>      desc: true,<br>    }}<br>  /&gt;<br>)<br>// → /shop?pageIndex=3&amp;includeCategories=%5B%22electronics%22%2C%22gifts%22%5D&amp;sortBy=price&amp;desc=true</pre><h4>Validation and Type Definition</h4><p>Validation and type definition of search params is using the validateSearch option of createFileRouteAPI. This allows for type safety when retrieving and manipulating search params in components.</p><pre>// /routes/shop.products.tsx<br><br>type ProductSearchSortOptions = &#39;newest&#39; | &#39;oldest&#39; | &#39;price&#39;<br><br>type ProductSearch = {<br>  page: number<br>  filter: string<br>  sort: ProductSearchSortOptions<br>}<br><br>export const Route = createFileRoute(&#39;/shop/products&#39;)({<br>  validateSearch: (search: Record&lt;string, unknown&gt;): ProductSearch =&gt; {<br>    // validate and parse the search params into a typed state<br>    return {<br>      page: Number(search?.page ?? 1),<br>      filter: (search.filter as string) || &#39;&#39;,<br>      sort: (search.sort as ProductSearchSortOptions) || &#39;newest&#39;,<br>    }<br>  },<br>})</pre><h3>Data Loading with Cache</h3><p>TanStack Router goes beyond the role of a simple loader with the capability of SWR caching, which is stored in-memory. This feature allows data to be preloaded and cached data to be displayed or previously retrieved data to be cached and used again.</p><h4>Dependency-based Stale-While-Revalidate Caching</h4><p><strong>The cache is controlled by the route dependencies.</strong> The dependencies here are the following elements:</p><ul><li><strong>Pathname of the route<br></strong><em>/posts/1 vs /posts/2</em></li><li><strong>Additional dependencies provided by loaderDeps<br></strong><em>loaderDeps: ({ search: { index, size } }) =&gt; ({ index, size })</em></li></ul><h4>Cache Control</h4><p>The cache in TanStack Router is similar to TanStack Query, and those familiar with TanStack Query can handle it with a lower learning cost.</p><p><strong>staleTime</strong></p><ul><li>The time until cached data is considered stale. The default is 0.</li></ul><p><strong>gcTime</strong></p><ul><li>The time until unused cache is discarded. The default is 30 min.</li></ul><h3>TanStack Query’s Suspense</h3><p>While we have been discussing TanStack Router so far, I would like to explain the suspense feature that became stable with TanStack Query v5.</p><p>The major difference between the usual useQuery and useSuspenseQuery is that <strong>there is no longer a need to account for the state which data is </strong><strong>undefined</strong>.</p><p>When using TanStack Query, we used to implement it such that a pendingComponent would be displayed when data does not exist, and an errorComponent would be shown in case of an error. The following code is an example of this.</p><pre>function Todos() {<br>  const query = useQuery({ queryKey: [&#39;todos&#39;], queryFn: getTodos })<br><br>  if (query.status === &quot;pending&quot;) {<br>    return &lt;Pending /&gt;<br>  }<br><br>  if (query.status === &quot;error&quot;) {<br>    return &lt;Error /&gt;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      Todo Items<br>    &lt;/div&gt;<br>  )<br>}</pre><p>However, when using useSuspenseQuery, <strong>there is no need to consider the state which data is </strong><strong>undefined</strong>, so the code changes as follows:</p><pre>function Todos() {<br>  const { data } = useSuspenseQuery({<br>    queryKey: [&#39;todos&#39;],<br>    queryFn: fetchTodos,<br>  })<br><br>  // 🎉 no need to handle loading or error states<br><br>  return (<br>    &lt;div&gt;<br>      { /* TypeScript knows data can&#39;t be undefined */ }<br>      {data.map((todo) =&gt; (<br>        &lt;div&gt;{todo.title}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>function App() {<br>  // 🚀 Boundaries handle loading and error states<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;ErrorBoundary fallback={&lt;div&gt;On no!&lt;/div&gt;}&gt;<br>        &lt;Todos /&gt;<br>      &lt;/ErrorBoundary&gt;<br>    &lt;/Suspense&gt;<br>  )<br>}</pre><p>Previously, there was a need to handle the states of “pending” and “error” within the Component itself. Now, <strong>it has become possible to manage these concerns separately</strong>.</p><ul><li>Pending State: Handled by the fallback of <strong>Suspense</strong>.</li><li>Error State: Handled by the fallback of <strong>ErrorBoundary</strong>.</li></ul><p>As some of you may have noticed, <strong>this separation of concerns aligns very well with the file-based approach of TanStack Router</strong>. With TanStack Router, it was possible to define a component, pendingComponent, and errorComponent for each route.</p><pre>// routes/posts.tsx<br>export const Route = createFileRoute(&#39;/posts&#39;)({<br>  component, // success<br>  errorComponent, // error<br>  pendingComponent, // pending<br>})</pre><p>This means that the handling of the pending and error states for useSuspenseQuery used within a component can be configured on a per-route basis with TanStack Router.</p><h4>Which to Use: Loader or TanStack Query?</h4><p>We’ve explained how TanStack Query’s suspense feature is compatible with TanStack Router. However, from the perspective of data fetching, it’s also possible with TanStack Router’s loader, which also has SWR caching capabilities.</p><p>So, how should we distinguish and utilize them?</p><p>The official documentation mentioned the advantages and disadvantages of TanStack Router’s Cache.</p><p><strong>Advantages of TanStack Router Cache</strong></p><ul><li>Easy to use out of the box</li><li>Allows for deduplication, preloading, and loading handling on a per-route basis</li><li>Automatically supports garbage collection</li></ul><p><strong>Disadvantages of TanStack Router Cache</strong></p><ul><li>No adapters or models for persistence</li><li>No cache sharing or deduplication across routes</li><li>Lacks APIs for updates</li></ul><p><strong>The loader is concerned with the target route, and cannot share caches between routes.</strong></p><p>Therefore, <strong>the presence of TanStack Query as an application state management tool is necessary</strong>, and it is required to be effectively combined with TanStack Router.</p><h4>Preloading Cache Data</h4><p><strong>TanStack Router has a built-in functionality for preloading</strong>. For example, when a user hovers over a &lt;Link&gt; intending to navigate to a different screen, it preloads the data required for that route.</p><p><a href="https://tanstack.com/router/latest/docs/framework/react/guide/preloading">Preloading | TanStack Router Docs</a></p><p>This feature is very powerful, and by combining it with TanStack Query, it can make data fetching more efficient and sometimes even solve the waterfall problem.</p><p><a href="https://tkdodo.eu/blog/seeding-the-query-cache#prefetching">Seeding the Query Cache</a></p><p>Here is a code example:</p><p>Prepare the data in advance with TanStack Router’s loader and save it in TanStack Query’s cache. Therefore, by the time useSuspenseQuery is called, the data is already ensured to be available.</p><pre>// src/routes/posts.tsx<br><br>const postsQueryOptions = queryOptions({<br>  queryKey: &#39;posts&#39;,<br>  queryFn: () =&gt; fetchPosts,<br>})<br><br>export const Route = createFileRoute(&#39;/posts&#39;)({<br>  // Use the `loader` option to ensure that the data is loaded<br>  loader: () =&gt; queryClient.ensureQueryData(postsQueryOptions),<br>  component: () =&gt; {<br>    // Read the data from the cache and subscribe to updates<br>    const posts = useSuspenseQuery(postsQueryOptions)<br><br>    return (<br>      &lt;div&gt;<br>        {posts.map((post) =&gt; (<br>          &lt;Post key={post.id} post={post} /&gt;<br>        ))}<br>      &lt;/div&gt;<br>    )<br>  },<br>})</pre><p><a href="https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#a-more-realistic-example-using-tanstack-query">External Data Loading | TanStack Router Docs</a></p><p><strong>Preload data with TanStack Router’s loader and manage the state of cached data with TanStack Query’s </strong><strong>useSuspenseQuery.</strong></p><h3>The directory design for TanStack Router</h3><p>So far, we have discussed the features of TanStack Router and its compatibility with TanStack Query. Finally, I will introduce the directory structure of TanStack Router that is explaining its characteristics and advantages.</p><p>The directory structure is as follows:</p><pre>.<br>├── __root.tsx // root file<br>├── posts<br>│   ├── -components // 🐢 UI components used within the route.<br>│   ├── -api // 🦋 API communication Hooks used within the route.<br>│   ├── -types // 🐠 Type definitions used within the route.<br>│   ├── -functions // 🦐 Functions used within the route.<br>│   ├── route.lazy.tsx // 🐕 Lazy Route<br>│   ├── route.tsx // 🦈 Critical Route<br>│   └── $postId // Similar to /posts.<br>│       ├── -components<br>│       ├── -api<br>│       ├── -types<br>│       ├── -functions<br>│       ├── route.lazy.tsx<br>│       └── route.tsx</pre><h4>Feature 1: Feature-based Directory Structure</h4><p>In the example provided, each route contains the following directories:</p><ul><li><strong>-components</strong>: UI components used within the route.</li><li><strong>-api</strong>: Hooks for API communications used within the route. APIs such as TanStack Query are utilized here.</li><li><strong>-types</strong>: Type definitions used within the route.</li><li><strong>-functions</strong>: Functions used within the route. Each function may have its unit tests implemented.</li></ul><p>This approach enables a <strong>feature-based design</strong>, as opposed to a layer-based approach where directories like components or api are placed at the top level of the hierarchy.</p><p>Of course, not all features will correspond directly to a route. In such cases, using a <strong>_prefix to group related concerns</strong> might be an effective strategy.</p><p><a href="https://dev.to/profydev/screaming-architecture-evolution-of-a-react-folder-structure-4g25">Screaming Architecture - Evolution of a React folder structure</a></p><h4>Feature 2: Route Hooks Usage is Limited to the Specific Route</h4><p>In TanStack Router, we can handle path parameters and search parameters in a type-safe by using Route Hooks that correspond to each specific route.</p><pre>export const Route = createFileRoute(&#39;/posts/$postId&#39;)({<br>  component: PostComponent,<br>})<br><br>function PostComponent() {<br>  const { postId } = Route.useParams()<br>  return &lt;div&gt;Post {postId}&lt;/div&gt;<br>}</pre><p>When the components used within a route are encapsulated as described in the directory design above, it is clear that Route Hooks specific to /posts are used for routes under /posts.</p><pre>.<br>├── pages<br>├── components<br>│   ├── Post.tsx // Are the Route Hooks for /posts used?<br>│   ├── Todo.tsx // Are the Route Hooks for /todos used?<br>│   ├── Form.tsx // ???<br>│   └── Card.tsx // ???</pre><p>Although it might be an extreme example, in a design where components are placed at the top hierarchy, it becomes challenging to discern where and which Route Hooks are being utilized.</p><p><strong>By focusing on a feature-based design, it becomes apparent that components used within a route are only concerned with that particular route.</strong></p><pre>.<br>├── posts<br>│   ├── -components // The Route Hooks for /posts are used.<br>│   │   ├── Card.tsx<br>│   │   └── Form.tsx<br>│   └── $postId <br>│       └── -components // The Route Hooks for /posts/$postId are used.</pre><h4>Feature 3: Clear Boundaries for Suspense</h4><p>We discussed how using TanStack Query’s useSuspenseQuery allows us to externalize the concerns for pending and error states, eliminating the need for the component side to anticipate cases which data is undefined.</p><p>Reiterating why it pairs well with TanStack Router, one reason is that you can define a pendingComponent and errorComponent for each route, which means there&#39;s no need to define custom Suspense boundaries.</p><p>Refer to the samples posted in the TanStack Router documentation for more information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kJ4D4kMI7dGh_I0s.png" /></figure><p>In the image above, there are Suspense boundaries indicated by red and blue frames, respectively. This means that the pending and error states occurring within the blue frame are handled by the processing defined in the /post/$postId route, while those occurring within the red frame are handled by the processing defined in the /posts route.</p><p>(Below is an actual code example.)</p><p><a href="https://stackblitz.com/github/tanstack/router/tree/main/examples/react/basic-react-query-file-based?embed=1&amp;theme=light">Router Basic React Query File Based Example - StackBlitz</a></p><h3>Summary</h3><p>In this session, we discussed the features of TanStack Router and its compatibility with TanStack Query, and finally introduced a directory design. While the evolution of frameworks like Next.js and Remix is remarkable, there has been a sense that the challenges of developing Single Page Applications (SPAs) with React have not been fully addressed.</p><p>However, the File-Based and high Developer Experience (DX) approach of TanStack Router introduced this time could be an effective choice in the selection of React libraries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7ecdc73550" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>