TanStack Router

그거아냐·2025년 2월 19일
0
post-thumbnail

TanStack Router 누구신지?

클라이언트 사이드 자바스크립트 어플리케이션 프레임워크입니다.

클라이언트 사이드 : 서버와 클라이언트 중에서 클라이언트 쪽에서의 처리를 의미

자바스크립트 : 자바스크립트

프레임워크 : 개발자가 원하는 기능 구현에만 집중하여 빠른 속도로 개발을 할 수 있도록 기본적인 기능을 갖추고 있는 뼈대를 의미하며, 프레임워크에 의존적이고, 프레임워크가 요구하는 규칙에 따라 개발해야 한다.

현재는 베타버전이지만 서버 사이드 기능을 포함한 TanStack Start도 있습니다.

TanStack Router는 react-router-dom처럼 별도의 코드를 통해 라우팅을 지정해주지 않아도 파일 기반으로 라우팅이 작동한다.

사용법

설치 명령어

npm install @tanstack/react-router
npm install -D @tanstack/router-plugin @tanstack/router-devtools

pnpm add @tanstack/react-router
pnpm add -D @tanstack/router-plugin @tanstack/router-devtools

yarn add @tanstack/react-router
yarn add -D @tanstack/router-plugin @tanstack/router-devtools

bun add @tanstack/react-router
bun add -D @tanstack/router-plugin @tanstack/router-devtools

deno add npm:@tanstack/react-router npm:@tanstack/router-plugin npm:@tanstack/router-devtools

폴더 구조

src
├── routes
│   ├── __root.tsx // 최상위 루트 파일
│   ├── about.tsx
│   ├── trip/
│   │   ├── index.tsx
│   │   └── ...
│   └── ... // 추가 라우팅 파일
├── main.tsx // 진입점 파일
├── routeTree.gen.ts // 자동 생성 파일
└── ...

__root.tsx

import { createRootRoute, Outlet } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools";

export const Route = createRootRoute({
  component: () => (
    <>
      <Outlet />
      <TanStackRouterDevtools />
    </>
  ),
});

위의 코드는 header와 footer가 없는 레이아웃입니다. 만약 header와 footer가 필요하다면 Outlet 위아래에 추가해주면 됩니다.

main.tsx

import { StrictMode } from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider, createRouter } from "@tanstack/react-router";

// Import the generated route tree
import { routeTree } from "./routeTree.gen";

// Create a new router instance
const router = createRouter({ routeTree });

// Register the router instance for type safety
declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}

// Render the app
const rootElement = document.getElementById("root")!;
if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <StrictMode>
      <RouterProvider router={router} />
    </StrictMode>
  );
}

routeTree.gen

pnpm dev 하면 자동 생성됩니다.

vite.config.js

import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/vite";
import viteReact from "@vitejs/plugin-react";
import { TanStackRouterVite } from "@tanstack/router-plugin/vite";

// https://vite.dev/config/
export default defineConfig({
  plugins: [TanStackRouterVite(), viteReact() ],
});

다른 플러그인이 있다면 추가!!

src/index.tsx

"/" 어플리케이션의 진입점이 될 페이지입니다.

import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/")({
  component: Index,
});

function Index() {
  return (
    <div className="p-2">
      <h3>Welcome Home!</h3>
    </div>
  );
}

다른 파일에서 해야할 것

import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/tripPage/")({
  component: TripPage,
});

페이지로 사용할 tsx 파일 상위에 작성해야될 코드입니다. 파일의 상위에 적어주면 createFileRoute에 명시한 주소로 라우팅이 됩니다.

TanStack Router를 사용할 이유

  1. 라우트 정의부터 url매개변수, 쿼리 스트링까지 완변한 typeScript 지원
  2. 라우트 객체를 기반으로 경로가 자동 완성되며, 잘못된 경로 사용시 타입 에러 발생
  3. useRouter를 사용해도 타입이 유지되어 버그가 방지됨
  4. Next.js 처럼 파일 기반이 아니라, 객체 기반으로 라우트를 정의
  5. 다이나믹 라우팅, 중첩 라우팅을 유연하게 설정 가능
  6. TanStack Query(React Query)와 같은 생태계라서 완벽호환
  7. 라우트 로딩시 데이터를 React Query로 사전 로딩가능
const routeTree = createRouteTree([
  {
    path: "/users",
    component: UsersPage,
    loader: async () => fetchUsers(), // React Query로 미리 데이터 가져오기
  },
]);
  1. React Route보다 가벼운 번들크기
profile
지금 하고 있는 그거 그거아냐

0개의 댓글