Login works (Chapter S2 16: DevTinder UI - Part 2), but two problems remain: refreshing the page logs you out, and anyone can open protected pages. In this chapter you'll restore the session when the app loads, redirect logged-out users, add logout, show the feed of developers, and build an edit profile page with a live preview.
In this chapter you'll learn
- why Redux state disappears on refresh, and how to restore the session from the server
useEffectfor fetching data when a component appears- protecting pages: redirecting to
/loginon a 401 - logout: calling the API, clearing Redux, redirecting
- a feed slice, a
Feedpage and a reusableUserCard - an edit profile form with a live preview and a success toast
Before you start: read Chapter S2 16: DevTinder UI - Part 2 (axios, withCredentials, Redux). The backend APIs used here come from Chapter S2 11: Diving into the APIs and Express router and Chapter S2 14: Building Feed API and Pagination.
Why a refresh logs you out
Redux state lives in the browser tab's memory. A page refresh restarts the JavaScript app, so the store starts empty again (user: null).
But the cookie survives a refresh: the browser keeps it, with the JWT inside (Chapter S2 10: Authentication, JWT & Cookies). So the session isn't really gone; the app just forgot who you are.
The frontend can't read an HttpOnly cookie to check, so the reliable way is to ask the server: call GET /profile/view. The browser attaches the cookie automatically.
200→ the token is valid: put the user back into Redux.401→ no valid token: send the user to/login.
useEffect: run code when a component appears
useEffect runs a function after the component renders. With an empty dependency array [], it runs once, when the component first appears (mounts). That's the place to fetch data.
useEffect(() => {
fetchUser();
}, []); // [] = run once, on mountuseEffect(() => {
fetchUser();
}, []); // [] = run once, on mountIn development, React's StrictMode (enabled by Vite's template in main.jsx) deliberately mounts components twice to help you find bugs, so you'll see each request twice in the Network tab. That doesn't happen in production builds.
Restoring the session in Body
Body is the layout around every page (Chapter S2 15: DevTinder UI - Part 1), so it's the right place to check the session once:
// src/components/Body.jsx
import { useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addUser } from "../utils/userSlice";
import NavBar from "./NavBar";
import Footer from "./Footer";
const Body = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const user = useSelector((store) => store.user);
const fetchUser = async () => {
if (user) return; // already in Redux (e.g. just logged in): no request needed
try {
const res = await axios.get(BASE_URL + "/profile/view", { withCredentials: true });
dispatch(addUser(res.data));
} catch (err) {
if (err.response?.status === 401) {
navigate("/login"); // not logged in: go to the login page
}
console.error(err);
}
};
useEffect(() => {
fetchUser();
}, []);
return (
<div>
<NavBar />
<Outlet />
<Footer />
</div>
);
};
export default Body;// src/components/Body.jsx
import { useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addUser } from "../utils/userSlice";
import NavBar from "./NavBar";
import Footer from "./Footer";
const Body = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const user = useSelector((store) => store.user);
const fetchUser = async () => {
if (user) return; // already in Redux (e.g. just logged in): no request needed
try {
const res = await axios.get(BASE_URL + "/profile/view", { withCredentials: true });
dispatch(addUser(res.data));
} catch (err) {
if (err.response?.status === 401) {
navigate("/login"); // not logged in: go to the login page
}
console.error(err);
}
};
useEffect(() => {
fetchUser();
}, []);
return (
<div>
<NavBar />
<Outlet />
<Footer />
</div>
);
};
export default Body;if (user) return;skips the request when the user is already loaded.err.response?.statusis how axios exposes the HTTP status of a failed request. The?.avoids a crash when there's no response at all (e.g. the server is down).- This is why the backend's
userAuthmust answer 401 for auth failures (Chapter S2 10: Authentication, JWT & Cookies): the frontend relies on it.
Redirecting in the frontend only decides what the user sees. It doesn't protect any data: anyone can call the API directly with Postman. The real protection is userAuth on the backend.
Logout
Three steps: tell the server, clear the store, go to the login page.
// src/components/NavBar.jsx
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { removeUser } from "../utils/userSlice";
const dispatch = useDispatch();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await axios.post(BASE_URL + "/logout", {}, { withCredentials: true }); // server clears the cookie
dispatch(removeUser()); // clear the user from Redux
navigate("/login");
} catch (err) {
console.error(err);
}
};
// in the dropdown:
// <li><a onClick={handleLogout}>Logout</a></li>// src/components/NavBar.jsx
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { removeUser } from "../utils/userSlice";
const dispatch = useDispatch();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await axios.post(BASE_URL + "/logout", {}, { withCredentials: true }); // server clears the cookie
dispatch(removeUser()); // clear the user from Redux
navigate("/login");
} catch (err) {
console.error(err);
}
};
// in the dropdown:
// <li><a onClick={handleLogout}>Logout</a></li>axios.post(url, body, config): the logout API has no body, so pass {} as the second argument; withCredentials goes in the third. A common mistake is passing the config as the second argument, which sends it as the body and no cookie.
On logout, also clear other user-specific data (like the feed below), so the next person who logs in on this browser doesn't see the previous user's data. Give each slice a "clear" reducer and dispatch them all.
The feed
A feed slice
// src/utils/feedSlice.js
import { createSlice } from "@reduxjs/toolkit";
const feedSlice = createSlice({
name: "feed",
initialState: null,
reducers: {
addFeed: (state, action) => action.payload,
removeUserFromFeed: (state, action) =>
state.filter((user) => user._id !== action.payload), // used in S2 19
removeFeed: () => null,
},
});
export const { addFeed, removeUserFromFeed, removeFeed } = feedSlice.actions;
export default feedSlice.reducer;// src/utils/feedSlice.js
import { createSlice } from "@reduxjs/toolkit";
const feedSlice = createSlice({
name: "feed",
initialState: null,
reducers: {
addFeed: (state, action) => action.payload,
removeUserFromFeed: (state, action) =>
state.filter((user) => user._id !== action.payload), // used in S2 19
removeFeed: () => null,
},
});
export const { addFeed, removeUserFromFeed, removeFeed } = feedSlice.actions;
export default feedSlice.reducer;Add it to the store next to user:
reducer: {
user: userReducer,
feed: feedReducer,
},reducer: {
user: userReducer,
feed: feedReducer,
},A reusable UserCard
// src/components/UserCard.jsx
const UserCard = ({ user }) => {
const { firstName, lastName, photoUrl, age, gender, about, skills } = user;
return (
<div className="card bg-base-300 w-96 shadow-sm">
<figure>
<img src={photoUrl} alt="photo" />
</figure>
<div className="card-body">
<h2 className="card-title">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
{skills?.length > 0 && <p>Skills: {skills.join(", ")}</p>}
<div className="card-actions justify-center my-4">
<button className="btn btn-primary">Ignore</button>
<button className="btn btn-secondary">Interested</button>
</div>
</div>
</div>
);
};
export default UserCard;// src/components/UserCard.jsx
const UserCard = ({ user }) => {
const { firstName, lastName, photoUrl, age, gender, about, skills } = user;
return (
<div className="card bg-base-300 w-96 shadow-sm">
<figure>
<img src={photoUrl} alt="photo" />
</figure>
<div className="card-body">
<h2 className="card-title">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
{skills?.length > 0 && <p>Skills: {skills.join(", ")}</p>}
<div className="card-actions justify-center my-4">
<button className="btn btn-primary">Ignore</button>
<button className="btn btn-secondary">Interested</button>
</div>
</div>
</div>
);
};
export default UserCard;{age && gender && <p>...</p>} is conditional rendering: the paragraph appears only when both values exist. The buttons get wired up in Chapter S2 19: DevTinder UI - Part 5.
The Feed page
// src/components/Feed.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addFeed } from "../utils/feedSlice";
import UserCard from "./UserCard";
const Feed = () => {
const feed = useSelector((store) => store.feed);
const dispatch = useDispatch();
const getFeed = async () => {
if (feed) return; // already loaded
try {
const res = await axios.get(BASE_URL + "/user/feed", { withCredentials: true });
dispatch(addFeed(res.data.data)); // the API sends { data: [...] }
} catch (err) {
console.error(err);
}
};
useEffect(() => {
getFeed();
}, []);
if (!feed) return null;
if (feed.length === 0) {
return <h1 className="flex justify-center my-10">No new users found!</h1>;
}
return (
<div className="flex justify-center my-10">
<UserCard user={feed[0]} />
</div>
);
};
export default Feed;// src/components/Feed.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addFeed } from "../utils/feedSlice";
import UserCard from "./UserCard";
const Feed = () => {
const feed = useSelector((store) => store.feed);
const dispatch = useDispatch();
const getFeed = async () => {
if (feed) return; // already loaded
try {
const res = await axios.get(BASE_URL + "/user/feed", { withCredentials: true });
dispatch(addFeed(res.data.data)); // the API sends { data: [...] }
} catch (err) {
console.error(err);
}
};
useEffect(() => {
getFeed();
}, []);
if (!feed) return null;
if (feed.length === 0) {
return <h1 className="flex justify-center my-10">No new users found!</h1>;
}
return (
<div className="flex justify-center my-10">
<UserCard user={feed[0]} />
</div>
);
};
export default Feed;The feed shows one card at a time (feed[0]), like Tinder. Make it the default page by adding it as the child route for / inside Body: <Route path="/" element={<Feed />} />.
Edit profile with a live preview
The profile page shows a form on the left and a UserCard preview on the right that updates as you type: the same component, fed with the form's state instead of saved data.
// src/components/EditProfile.jsx (main parts)
const EditProfile = ({ user }) => {
const [firstName, setFirstName] = useState(user.firstName);
const [lastName, setLastName] = useState(user.lastName || "");
const [photoUrl, setPhotoUrl] = useState(user.photoUrl);
const [age, setAge] = useState(user.age || "");
const [gender, setGender] = useState(user.gender || "");
const [about, setAbout] = useState(user.about || "");
const [error, setError] = useState("");
const [showToast, setShowToast] = useState(false);
const dispatch = useDispatch();
const saveProfile = async () => {
setError("");
try {
const res = await axios.patch(
BASE_URL + "/profile/edit",
{ firstName, lastName, photoUrl, age, gender, about },
{ withCredentials: true }
);
dispatch(addUser(res.data.data)); // update the user everywhere (NavBar too)
setShowToast(true);
setTimeout(() => setShowToast(false), 3000);
} catch (err) {
setError(err?.response?.data || "Something went wrong");
}
};
return (
<div className="flex justify-center gap-10 my-10">
{/* form: one controlled input per field, like the login form, plus a Save button */}
<UserCard user={{ firstName, lastName, photoUrl, age, gender, about }} />
{showToast && (
<div className="toast toast-top toast-center">
<div className="alert alert-success">
<span>Profile saved successfully.</span>
</div>
</div>
)}
</div>
);
};// src/components/EditProfile.jsx (main parts)
const EditProfile = ({ user }) => {
const [firstName, setFirstName] = useState(user.firstName);
const [lastName, setLastName] = useState(user.lastName || "");
const [photoUrl, setPhotoUrl] = useState(user.photoUrl);
const [age, setAge] = useState(user.age || "");
const [gender, setGender] = useState(user.gender || "");
const [about, setAbout] = useState(user.about || "");
const [error, setError] = useState("");
const [showToast, setShowToast] = useState(false);
const dispatch = useDispatch();
const saveProfile = async () => {
setError("");
try {
const res = await axios.patch(
BASE_URL + "/profile/edit",
{ firstName, lastName, photoUrl, age, gender, about },
{ withCredentials: true }
);
dispatch(addUser(res.data.data)); // update the user everywhere (NavBar too)
setShowToast(true);
setTimeout(() => setShowToast(false), 3000);
} catch (err) {
setError(err?.response?.data || "Something went wrong");
}
};
return (
<div className="flex justify-center gap-10 my-10">
{/* form: one controlled input per field, like the login form, plus a Save button */}
<UserCard user={{ firstName, lastName, photoUrl, age, gender, about }} />
{showToast && (
<div className="toast toast-top toast-center">
<div className="alert alert-success">
<span>Profile saved successfully.</span>
</div>
</div>
)}
</div>
);
};// src/components/Profile.jsx
const Profile = () => {
const user = useSelector((store) => store.user);
return user && <EditProfile user={user} />;
};// src/components/Profile.jsx
const Profile = () => {
const user = useSelector((store) => store.user);
return user && <EditProfile user={user} />;
};- The form's initial values come from the user in Redux.
- The backend validates everything again (Chapter S2 08: Data Sanitization & Schema Validations, Chapter S2 11: Diving into the APIs and Express router); if it rejects the update, the API's error message is shown under the form.
- After saving,
dispatch(addUser(...))updates Redux, so the NavBar's name and photo change instantly. ProfilerendersEditProfileonly once the user is loaded (user && ...), so the form never starts with empty values.
We built Body, Feed, UserCard and EditProfile from this chapter in a test project (React 19, Redux Toolkit 2, React Router 7) to make sure they compile.
Common mistakes
- Expecting Redux to survive a refresh: restore it from
/profile/view. axios.post(url, { withCredentials: true }): the config ends up as the body; the cookie isn't sent.- Redirecting on every error: only a 401 means "not logged in"; a 500 or a network error doesn't.
- Not clearing user-specific slices on logout.
- Forgetting
useEffect's dependency array: the fetch runs after every render, in an endless loop. - Treating frontend redirects as security.
Key takeaways
- Redux is in memory (lost on refresh); the cookie survives. Restore the session by calling
GET /profile/viewon load. useEffect(fn, [])runs once on mount: the place for initial data fetching.- On 401, redirect to
/login. Frontend checks control the UI; backend checks are the real protection. - Logout:
POST /logout(with credentials) → clear Redux → go to/login. - A
UserCardcomponent is reused for the feed and the live profile preview. - After a successful edit, dispatch the updated user so every component re-renders.
Interview questions
Q1. How do you keep a user logged in after a page refresh in a React app?
Keep the session in a place that survives the refresh, an HttpOnly cookie, and restore the client state on load: call an endpoint like /profile/view (or /me) in a top-level component's useEffect. If it returns the user, put it back in the store; on 401, redirect to login. Avoid storing tokens in localStorage just to survive refreshes.
Q2. What is useEffect, and what does the dependency array do?
useEffect(fn, deps) runs side effects (fetching, subscriptions, timers) after render. The dependency array controls when it re-runs: [] means once after mount; [a, b] means whenever a or b changes; no array means after every render. It can return a cleanup function, which runs before the next effect and on unmount.
Q3. How do you protect routes in a React app?
Check the auth state before rendering protected pages: for example a layout or wrapper component that loads the current user and redirects to /login (with navigate or <Navigate to="/login" />) when there is none. This only controls the UI; every protected API must also verify authentication and authorization on the server.
Q4. Why does React StrictMode run effects twice in development?
StrictMode intentionally mounts, unmounts and re-mounts components in development to surface effects that don't clean up properly or aren't safe to repeat. It doesn't happen in production builds. Effects should be written so that running them twice is harmless.
Q5. How do you handle API errors with axios?
axios rejects the promise for network errors and for non-2xx responses. In catch, err.response exists if the server answered (with status, data and headers); if it's missing, the request never got a response (network error, CORS, timeout). Show err.response.data messages to the user, and branch on status (401 → login, 404 → not found, ≥500 → "try again later").
Q6. What is conditional rendering in React?
Rendering different UI depending on state or props, using JavaScript expressions: condition && <Component />, a ternary cond ? <A /> : <B />, or an early return (if (!feed) return null;). Watch out for 0 && ..., which renders 0; use a boolean like items.length > 0 && ....
What's next
Users can see the feed and edit their profile. In Chapter S2 18: DevTinder UI - Part 4 you'll build the Connections page and the Requests page, where users accept or reject the requests they've received.