Version
- React 19
- TanStack Router 1
- Zustand 5
로그인, 인증 관련하여 Zustand를 사용하여 관리할 예정이다.
TanStack Router 내부에서 사용하는 beforeLoad, loader, onLoad 등의 lifecycle 함수는 React 컴포넌트가 아니기 때문에 React hook을 직접 사용할 수는 없고 Router context에 React context를 주입하면 된다고 한다.
App.tsx
import { RouterProvider } from '@tanstack/react-router';
import { createAppRouter } from './router/router';
import { useAuthStore } from '@/stores/authStore';
const App = () => {
const auth = useAuthStore();
const router = createAppRouter(auth);
return <RouterProvider router={router} />;
};
export default App;
TanStack Router 예제에서는 React context를 사용했다면, 나는 Zustand를 사용했다.
useAuthStore에는 로그인 여부를 저장하는 isLoggedIn이 있다.
Router.ts
import { createRouter } from '@tanstack/react-router';
import { routeTree } from './routeTree';
import type { AuthState } from '@/types/authState.types';
export const createAppRouter = (auth: AuthState) =>
createRouter({
routeTree,
context: { auth },
});
앱라우터를 생성할 때 context에 인증 상태를 담아줬다.
그리고 인증이 필요한 라우트에 beforeLoad를 추가하면 된다.
otherPage.tsx
import { createRoute, redirect } from '@tanstack/react-router';
import { parentRoute } from '@/router/parent';
import OtherPage from '@/pages/OtherPage';
import type { AuthState } from '@/types/authState.types';
export const otherPageRoute = createRoute({
getParentRoute: () => parentRoute,
path: '/other',
component: OtherPage,
beforeLoad: ({ context, location }) => {
const { auth } = context as { auth: AuthState };
if (!auth.isLoggedIn) {
throw redirect({
to: '/login',
search: { redirect: location.href },
});
}
},
});
auth의 isLoggedIn의 값을 확인하여 login 페이지로 이동시킨다.
로그인 되지 않았을 때 other 페이지로 이동하려고 하면 로그인 페이지로 리다이렉트 되는 것을 확인했다.
로그인 페이지에서 로그인을 하면 other 페이지로 이동하지 않고, isLoggedIn의 값만 바뀌는 문제가 있다.
페이지 이동을 먼저 시도하고 이후에 상태 값이 바뀐 것이 원인으로 보인다.

로그인 페이지에서 로그인 성공 후 바로 페이지 이동을 하는 것이 아닌 uesEffect를 사용해보았다.
const { signin, isLoggedIn } = useAuthStore();
const onSubmit = (data) => {
// 로그인 시도
console.log('로그인 시도:');
// 생략
signin();
// navigate({ to: '/other' }) <- 이전 코드
};
useEffect(() => {
if (isLoggedIn) navigate({ to: '/other' });
}, [isLoggedIn]);

이게 맞게 한건진 모르겠지만 일단 동작은 한다!
끝!
반응형
'공부합시다 > React' 카테고리의 다른 글
| 라이브러리 없이 Drag&Drop으로 리스트 순서 바꾸기 (0) | 2025.03.21 |
|---|---|
| 이벤트 오작동 시 Event.preventDefault() 적용 (0) | 2025.03.20 |
| [기본 개념] React (1) | 2025.03.17 |
| [React] webpack < 5 used to include polyfills for node.js core modules by default. (2) | 2022.11.28 |
| [React] Router 추가하기 (0) | 2022.11.25 |