Describe a common strategy for implementing protected (authenticated) routes within a React application using React Router v6.

React JS interview question for Advanced practice.

Answer

A common strategy for handling protected routes is to create a reusable wrapper component, often called ProtectedRoute, that encapsulates the authentication logic. This component does the following: 1. It checks for the user's authentication status (e.g., from a context, a hook, or local storage). 2. If the user is authenticated, it renders its children (or uses an <Outlet / for nested routes). 3. If the user is not authenticated, it renders a <Navigate component to redirect them to the login page. Example Implementation: ProtectedRoute.js jsx import { Navigate, Outlet } from 'react-router-dom'; // Assume useAuth() is a custom hook that returns { user: ... } or { user: null } import { useAuth } from './AuthContext'; function ProtectedRoute() { const { user } = useAuth(); if (!user) { // If not authenticated, redirect to the /login page return <Navigate to="/login" replace /; } // If authenticated, render the child routes return <Outlet /; } export default ProtectedRoute; App.js (Route Setup) jsx <Routes <Route path="/login" element={<LoginPage /} / {/ Routes nested under ProtectedRoute require authentication /} <Route element={<ProtectedRoute /} <Route path="/dashboard" element={<Dashboard /} / <Route path="/profile" element={<Profile /} / </Route </Routes This approach is clean and scalable because the authentication logic is centralized in ProtectedRoute, and routes are protected declaratively in the main router setup.

Explanation

A common pattern for protected routes is to create a wrapper component that conditionally renders either the child component or a <Navigate component based on authentication state.

Related Questions