Implementing Protected Routes and Authentication in React (2026 Edition)
This is an updated rewrite of my 2021 article on protected routes . A lot has changed in the React ecosystem since then. React Router moved from v5 to v7, class components have faded out, and the patterns we use for authentication state have matured. This version reflects how protected routes are built in modern React applications. Almost every web application requires some form of authentication to prevent unauthorized users from accessing parts of the application meant for signed-in users only. In this tutorial, I'll show how to set up an authentication flow and protect routes from unauthorized access using modern React patterns: function components, hooks, React Router v6+, and the Context API. First things first Install the dependency: npm i react-router-dom That's it. React Router v6 and above ships as a single package, so you no longer need to install react-router and react-router-dom separately. It is worthy of note that we will not be using Redux for authentication state in this version. For something as simple as "is the user logged in?", React's built-in Context API is the standard approach today. Redux still has its place, but it is overkill here. The Auth Context Instead of writing to localStorage directly from components and reading it in random places, we centralize authentication state in a context. This gives us a single source of truth and a clean useAuth() hook we can call anywhere in the app. Create ./src/auth/AuthContext.jsx : import { createContext , useContext , useState } from " react " ; const AuthContext = createContext ( null ); export function AuthProvider ({ children }) { const [ user , setUser ] = useState (() => { // Rehydrate on page refresh const saved = localStorage . getItem ( " user " ); return saved ? JSON . parse ( saved ) : null ; }); const login = async ( username , password ) => { // In a real app, this is an API call to your backend. // We simulate it here with hardcoded credentials. if ( username . toLowerCase () === " admin