This demonstrates authentication and protected routing in a modern React application using Context API, useReducer, and React Router. It also introduces a custom useLocalStorage hook to persist user login across page reloads.
- User credentials are mocked for simplicity.
- On login, user data is saved to:
React Context(for app-wide access)localStorage(for persistence on refresh)
- Only accessible when a user is authenticated.
- Redirects to
/loginif user is not logged in.
| Feature | Description |
|---|---|
Context API |
Central store for user & auth state |
useReducer |
Used for scalable auth state management |
localStorage |
Data persists even after refresh |
useLocalStorage |
Custom reusable hook for local storage get/set/remove |
React Router |
Dynamic routing with protected routes |
src/
โ
โโโ components/
โ โโโ Login.tsx
โ โโโ Profile.tsx
โ
โโโ context/
โ โโโ AuthContext/
โ โโโ AuthContext.tsx
โ โโโ AuthContextType.ts
โ โโโ authReducer.ts
โ
โโโ hooks/
โ โโโ useAuth.ts โ Custom hook to access AuthContext
โ โโโ useLocalStorage.ts โ Custom hook to resue localStorage logic
โ
โโโ routes/
โ โโโ constant.ts
โ โโโ publicRoutes.ts
โ โโโ privateRoutes.ts
โ
โโโ styles/
โ โโโ Login.ts
โ โโโ Profile.ts
โ
โโโ types/
โ โโโ User.ts
โ
โโโ App.tsx
- react
- react-router
- auth-context
- role-based-access
- localstorage
- context-api
- use-reducer
- protected-routes
- react-hooks
This project helps you understand React application with global state, and protected routes.
Feel free to fork and โญ๏ธ this repo if it helps!