🧭 Introduction
In real-world React applications, users should remain logged in even after refreshing the page or reopening the browser. If your app forgets the user on refresh, it leads to a poor user experience.
To solve this problem, we use:
- Context API → for global authentication state
- LocalStorage / SessionStorage → for session persistence
In this lesson, you will learn:
- What session handling is
- Difference between LocalStorage and SessionStorage
- How Context API manages authentication state
- How to persist login using LocalStorage
- A complete login–logout session flow
❓ What is Session Handling?
Session handling means:
Managing and remembering the user’s login state across pages, refreshes, and browser restarts.
Without session handling ❌
- User logs out on page refresh
- State resets to default
With session handling ✅
- User stays logged in
- App remembers authentication state
🗄 LocalStorage vs SessionStorage
| Feature | LocalStorage | SessionStorage |
|---|---|---|
| Data persists on refresh | ✅ Yes | ✅ Yes |
| Data persists after browser close | ✅ Yes | ❌ No |
| Storage limit | ~5MB | ~5MB |
| Best use case | Login session | Temporary session |
👉 Most authentication systems use LocalStorage.
🧠 Why Combine Context API with LocalStorage?
❌ Using only LocalStorage
- No automatic UI updates
- Manual checks in every component
- Messy logic
✅ Using Context API + LocalStorage
- Global auth state
- Automatic re-render on login/logout
- Centralized authentication logic
- Clean and scalable architecture
🔐 Authentication Flow (Concept)
Login
→ Save user data in LocalStorage
→ Update Context API state
→ App re-renders automatically
Refresh
→ Context loads data from LocalStorage
→ User remains logged in
Logout
→ Clear LocalStorage
→ Reset Context state
→ Redirect to Login
🏗 Project Structure
src/
├── context/
│ └── AuthContext.jsx
├── components/
│ ├── Login.jsx
│ └── Dashboard.jsx
└── App.jsx
🛠 Step-by-Step Implementation
✅ Step 1: Create Auth Context
📄 context/AuthContext.jsx
import { createContext, useState, useEffect } from "react";
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
// Restore session on page refresh
useEffect(() => {
const storedUser = localStorage.getItem("user");
if (storedUser) {
setUser(JSON.parse(storedUser));
}
}, []);
// Login handler
const login = (userData) => {
localStorage.setItem("user", JSON.stringify(userData));
setUser(userData);
};
// Logout handler
const logout = () => {
localStorage.removeItem("user");
setUser(null);
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
export default AuthContext;
✅ Step 2: Wrap App with AuthProvider
📄 App.jsx
import { AuthProvider } from "./context/AuthContext";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
function App() {
return (
<AuthProvider>
<Login />
<Dashboard />
</AuthProvider>
);
}
export default App;
✅ Step 3: Login Component (Create Session)
📄 components/Login.jsx
import { useContext } from "react";
import AuthContext from "../context/AuthContext";
const Login = () => {
const { login } = useContext(AuthContext);
const handleLogin = () => {
const userData = {
name: "Avni",
role: "Admin"
};
login(userData);
};
return <button onClick={handleLogin}>Login</button>;
};
export default Login;
✅ Step 4: Dashboard Component (Use Session)
📄 components/Dashboard.jsx
import { useContext } from "react";
import AuthContext from "../context/AuthContext";
const Dashboard = () => {
const { user, logout } = useContext(AuthContext);
if (!user) {
return <p>Please login to continue</p>;
}
return (
<>
<h2>Welcome, {user.name} 👋</h2>
<p>Role: {user.role}</p>
<button onClick={logout}>Logout</button>
</>
);
};
export default Dashboard;
🔄 What Happens on Page Refresh?
1️⃣ React app reloads
2️⃣ Context useEffect() runs
3️⃣ Data is read from LocalStorage
4️⃣ Auth state is restored
5️⃣ User stays logged in
⚠ Security Considerations (Important)
❗ Never store passwords in LocalStorage
❗ Store only tokens or minimal user info
❗ Clear storage on logout
❗ Always use HTTPS in production
❓ FAQs — LocalStorage & Session Handling
🔹 Why not use only LocalStorage?
LocalStorage does not trigger UI updates. Context API does.
🔹 Can I use SessionStorage instead?
Yes, if you want the user to logout automatically when the browser closes.
🔹 Is Context API enough for authentication?
Yes, for small to medium apps. Large apps may use Redux or other libraries.
🔹 Where should authentication logic live?
Inside a dedicated AuthContext.
🔹 What happens if LocalStorage is cleared?
User is logged out automatically.
🎯 Best Practices
✅ Keep auth logic inside Context
✅ Use LocalStorage only for persistence
✅ Clear data on logout
✅ Combine with Protected Routes
🧠 Quick Recap
✔ Context API manages global auth state
✔ LocalStorage persists login session
✔ useEffect restores session on refresh
✔ Clean, real-world authentication flow
🎉 Conclusion
Using Context API with LocalStorage is one of the most practical and widely used patterns in real-world React applications. It allows you to manage authentication globally while keeping the user logged in across refreshes.
After this lesson, you’re ready to build professional login systems and dashboards 🚀
👉 Next Lesson (SECTION 5):
Lesson 27 — useReducer Hook (Advanced State Management)