Tanstack router is an alternative to the react-router, de-facto standard for routing in react applications. The Tanstack Team published the first stable version in December 2023. The router brings many interesting concepts, for example a constant type of protection, the file-based passage and the apprehension of the state outsourcing parts in the URL.
Advertisement
Nils Hartman is a freelance software developer and coach that focuses on Java in the backnd and reacts in the front, for which he also imparts workshops and training.
The Tanestac Library (East Reaction Querry) is now available in version 5 and already very popular to bring data. Your flexibility, a sophisticated cashing mechanism and high type of protection are also to be emphasized.
Two libraries can be used independently, but can also work very well together and in some cases, global state management equipment such as plowing, status or even Redux can change the use.
Tanstack is a collection of open sources libraries for the development of single-page applications (Spa). In addition to Tanstack router and Tanstack Query, for example, Tanstack Table and Tanstack Size. Many libraries working under the “brand” are introduced for reaction, angular, VU and other spa libraries. However, the Tanstack router works only with the response. Tanastac Libraries became popular with tables and queries, which were initially available only for reacts and then called react tables and react query. The initiator of the two libraries, Tanner Linsley introduced the term Tanestac to clarify that the libraries are no longer available for reacts.
Tanestac router and tanestac querry in action
A react single-page application is used for the administration of tasks (TAKS) to display two libraries. The functions can be displayed in a sortable list and in one or wide performance. Work can also be attached for quick access.
The application is certainly not complete and with the functions of this range it will probably be easier to create compared to the classic server -Side web application. However, such an application in real life will possibly have other interactive characteristics that will make development correct as a spa (for example, making and editing tasks). The bottom attention is deliberately on the subjects of navigation (routing) and works with server -sud data. Source code of sample application Available on github,
Tanstack router works, similar to server -wheat router. The structure of the file system, ie the name of organization and files in the folder, plays an important role. By the convention, the router can get an application in the URL or paths and what should happen when a path is called in the browser. It should be noted that the file system only plays a role in development and produces time (a plug-in is used for Vite). In the runtime, the Tanestac router is a purely client -wheat, such as a react router.
Until otherwise configured, the directory in the router project explains all files under the SRC/routes, which in the form of routes (see illustration). For better readability, overraching directory in the following path.
Guide Directory of prepared application
(Image: Nils Heartman)
In the first phase, there should be two routes in the sample application which one “about us” (route: "/about"
) And a “data security” page (route: "/privacy"
) represent. For this purpose, two files with the name of the related route are to be created. The Vite plug-in recognizes these files and generates code to configure the passage, which can be adjusted to the will. As a rule, it gives component
Along with the router router -the react component should be presented while calling the route in the browser.
Regarding the listing (simplified) routes and shows the code of and /privacy:
// src/routes/about.tsx
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/about")({
component: AboutRouteComponent,
});
function AboutRouteComponent() {
return About us { /* ... */ }
;
}
// src/routes/privacy.tsx
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/privacy")({
component: PrivacyRouteComponent,
});
function PrivacyRouteComponent () {
return Privacy { /* ... */ }
;
}
The router supports the code division by the house: Vite plug-in each collected the JavaScript code of individual routes in its own bundle. The browser only loads when the related route is called (lazy loading). This makes it possible to significantly reduce the amount of JavaScript code which the browser initially loads and executes when the application begins and gives considerable speed to the onset of the application. Code division can be automatically activated for all routes by configuration. Alternatively, a root file with file extension can be activated for the division for file .lazy.tsx root (about. Lazy.TSX).
/The route about the following is shown as follows:

Regarding the route of the route
(Image: Nils Heartman)
Type -Seep Navigation
The link component of the router allows you to reach the next when using a route. Among other things, this component is waiting to
-Poptory, which indicates the target route) href
-Ttribut on HTML -A element). The following list shows the code for the listing component GlobalNavBar
This represents the navigation line of the application. Here are two links that indicate almost or privacy route. Property activeProps
The settings of the properties that routers are applied only when the link is activated. An active link is a link that points to a passage that has just been provided. This means that the current passage can be highlighted into a navigation line, for example.
export default function GlobalNavBar() {
return (
);
}
A special feature of the router is its consistent type of protection. to
-Poptory knows all the routes of the application and only accept valid values, that is, the route that actually exists. To enter the correct value, the typescript can support, for example, with the completion of the code, as the illustration shows. The Vite plug-in automatically produces the related types for this. This ensures that people actually fit existing routes in the project and after a refractor, for example, do not deviates.
Code complete for information on valid route
(Image: Nils Heartman)
Call server -whee data with Tanstack Query Query
The sample application should receive two other routes that represent the list of tasks or single functions. To explain how the application for this loads the data from the backnd through the rest of the API, only the list performance should only work in the beginning. It must be on the path "/tasks"
Call a call (see illustration). To do this, create a new directory with the name of the route (functions). It contains the file index.tsx, in which the route configuration is located. Here also, Vite Plug-in produces the required boiler platform code and also expands the type of type, so that GlobalNavBar
-K component can now also have a link to tastes without triggering compilation error.
/There is a list of work routes works.
(Image: Nils Heartman)
The Tanstack Querry work is to read data in the work component. To show the functionality of the tanestac querry in separation from the router, it reads the data here as an example in the component. A subsequent example will use the load function of a passage.
Tanestac Querry server provides several ways to fulfill the requests and read data. For this, the central object application is generated when it starts. QueryClient
It manages cash and other global settings. He also offers a reaction-independent API to execute questions. As a rule, however, query clients are not used directly within the feedback components. Instead, reaction-specific hook functions such as useQuery
And useSuspenseQuery
used. The first way is useQuery
-Heke has been shown. The following example refers to the use of suspense feature by reacting with tanastac querry.
Despite the path through which developers want to run a query, you will have to make at least two settings, query options. On the one hand, they specify a function – query function – which is responsible for charging data. On the other hand, a query key must define where the data read in the cash must be stored. Shows a simplified use of listing useQuery
,
function TaskListRouteComponent() {
const result = useQuery({
queryKey: ("tasks", "list"),
queryFn(): Promise {
return fetch("http://api.tasks").then(res => res.json());
},
});
if (result.isPending) {
// Daten werden noch gelesen
return
}
if (result.isSuccess) {
// Daten wurden erfolgreich gelesen
return
}
// Fehler
return "Die Tasks konnten nicht gelesen werden";
}
The contract for the query function is very simple: it has to make a promise in which the data is read. If the function cannot read data, for example, because there is a problem with the network or the requested closing point does not work, it should throw an error. Querry key is used to write reed data in cache and then re -read.
If the work route is called, the router renders TaskListRouteComponent
And the query is executed. If the cash has no data yet, it provides useQuery
-To back one item back "isPending"
-In the information true
Is set. The component then shows a placeholder. After successfully reading the data, the component is re-enhanced-it corresponds to specific response behavior while changing the position of an ingredient.
Is that useQuery
Returned objects now include information among other things, information "isSuccess"
It suggests that data is then available "data"
Are available. Through the information of these (and other) status, an component can react exactly to the individual stages of the life cycle of request and output the appropriate information on the surface.
Tanestac in its global cash discontinue the reed data. When the component is rendering, the library checks whether the data is in cache (depending on the query key). If you are already there, the data will be returned from the cash. In the sample application, it means that the data comes from the cache directly when changing between the task list and the other route and back to the work list. Even if many components shown at the same time queries for the same query key, the tanastac query ensures that the query is not done many times and all the components get the same stand from the cash.
By default, the data read in cache remains, but is immediately considered a “stale”, ie old. Consequently, the component gets the data back from the cache when querring occurs, but the query function runs again to update the data in the cache in parallel to the background. Therefore the data can usually be displayed very quickly when changing between routes. The presentation automatically updates as Query has read new data in the background. How long the data in the cash will last, when you are considered old and under which circumstances you are recited again, the global can be set very flexible per querry to map almost all comprehensive requirements.
(Image: WD Ashari/Shutterstock.com)
ENTERJS 2025 Manhem takes on May 7 and 8 on 8th May. The conference provides a comprehensive approach to the JavaScript-based enterprise world. Meditation is not only on programming languages ​​on JavaScript and Typscript, but also on framework and tools, accessibility, practical reports, UI/UX and security.
Highlights from the program:
Tickets are At the cost of the initial bird Available in online shop.