Blog>
Snippets

Using Hooks for State Management in Authenticated Routing

Illustrate the use of React hooks with TanStack Router for managing authentication state and protecting routes based on user status.
import { useState, useEffect, useContext, createContext } from 'react';
import { useNavigate } from 'tanstack-router';

// Authentication context
const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const navigate = useNavigate();

    useEffect(() => {
        // Check authentication status
        const isAuth = localStorage.getItem('isAuthenticated') === 'true';
        setIsAuthenticated(isAuth);
    }, []);

    const signIn = () => {
        localStorage.setItem('isAuthenticated', 'true');
        setIsAuthenticated(true);
        navigate('/dashboard'); // Redirect to dashboard after login
    };

    const signOut = () => {
        localStorage.removeItem('isAuthenticated');
        setIsAuthenticated(false);
        navigate('/login'); // Redirect to login page after logout
    };

    return (
        <AuthContext.Provider value={{ isAuthenticated, signIn, signOut }}>
            {children}
        </AuthContext.Provider>
    );
};
This code snippet defines an AuthProvider component using a React context to manage authentication state across the application. It utilizes TanStack Router's useNavigate hook for navigating between routes programmatically.
import { useContext } from 'react';
import { createBrowserRouter, Route, RouterProvider } from 'tanstack-router';
import { AuthProvider, AuthContext } from './AuthProvider';
import Dashboard from './Dashboard';
import Login from './Login';

// A route guard component
const RequireAuth = ({ children }) => {
    const { isAuthenticated } = useContext(AuthContext);
    const navigate = useNavigate();

    if (!isAuthenticated) {
        navigate('/login', { replace: true });
        return null;
    }

    return children;
};

// Router setup
const router = createBrowserRouter([
    {
        path: '/',
        element: <RequireAuth><Dashboard /></RequireAuth>,
    },
    {
        path: '/login',
        element: <Login />,
    }
]);

// App component
export default function App() {
    return (
        <AuthProvider>
            <RouterProvider router={router} />
        </AuthProvider>
    );
}
This snippet sets up TanStack Router with a simple authenticated routing mechanism. It showcases the use of the RequireAuth component to protect routes that require authentication, redirecting unauthenticated users to the login page.