Redux & Redux Toolkit
/Intermediate
Protected Routes
Definition
React Router components that read the authentication status from the Redux store and decide whether to render the requested page or redirect the user to a login screen.
Explain Like I'm New
A digital bouncer. If a user tries to type `/admin` into the URL bar, the Protected Route component asks Redux: 'Is this person logged in?'. If Redux says false, the Protected Route kicks them back to the `/login` page.
Real World Example
Wrapping your `/dashboard`, `/settings`, and `/billing` components inside a `<RequireAuth>` wrapper component.
Common Use Cases
- •Restricting application access
Interactive Example
import { Navigate, Outlet } from 'react-router-dom'; import { useSelector } from 'react-redux'; // A Wrapper Component for Protected Routes const RequireAuth = () => { // Ask Redux if the user is allowed in const isLoggedIn = useSelector((state) => state.auth.isLoggedIn); if (!isLoggedIn) { // If not logged in, kick them to the login page. // We use 'replace' to prevent them from hitting the back button. return <Navigate to="/login" replace />; } // If logged in, render the child routes (the actual page they wanted)! return <Outlet />; }; /* Usage in Router: <Route element={<RequireAuth />}> <Route path="/dashboard" element={<Dashboard />} /> <Route path="/settings" element={<Settings />} /> </Route> */
Interview Questions
basic
- What Redux hook is used inside a Protected Route to check if the user is authenticated?
intermediate
- If a user tries to visit `/dashboard` and is kicked to `/login`, how do you automatically send them back to `/dashboard` after they log in?