Adding Logout
Logout ends a user's authenticated session so the app stops treating them as signed in. In a token-based app, that usually means clearing the stored token and user data on the frontend, updating the shared authentication state so the interface changes straight away, and sending the user to a public page. Once login and redirects are in place, logout is the piece that completes the cycle.
What logging out actually needs to clear
When a user logs in, your app typically saves three things: the token itself, some user details such as an id or name, and sometimes an expiry time. Logout must remove all of them from wherever they live, which could be React state, localStorage or both. If any piece is left behind, a page refresh could quietly restore the user's session.
With JWTs, the server usually does not keep a list of active tokens, so the frontend deleting its copy is the main step. If your backend uses refresh tokens or server sessions, call a logout endpoint too so the server can revoke them.
Putting logout in the auth context
A good place for the logout function is the same context that provides login. That way any component, such as a navigation bar or a settings page, can call it without passing props through many layers.
import { createContext, useCallback, useState } from 'react';
export const AuthContext = createContext({
token: null,
isLoggedIn: false,
login: () => {},
logout: () => {},
});
export function AuthProvider({ children }) {
const [token, setToken] = useState(() => localStorage.getItem('token'));
const login = useCallback((newToken) => {
localStorage.setItem('token', newToken);
setToken(newToken);
}, []);
const logout = useCallback(() => {
localStorage.removeItem('token');
setToken(null);
}, []);
return (
<AuthContext.Provider value={{ token, isLoggedIn: !!token, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Wiring the button and redirecting
The logout button only needs to call logout and then navigate somewhere public. With React Router, the useNavigate hook handles that. Use replace: true so the browser's back button does not return the user to a protected page they can no longer use.
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from './AuthContext';
function NavBar() {
const { isLoggedIn, logout } = useContext(AuthContext);
const navigate = useNavigate();
function handleLogout() {
logout();
navigate('/login', { replace: true });
}
return (
<nav>
{isLoggedIn && <button onClick={handleLogout}>Log out</button>}
</nav>
);
}
Common mistake: clearing storage but not state
A frequent bug is removing the token from localStorage while leaving the React state untouched. The page still shows the "Log out" button and protected content until the user refreshes, because components re-render from state, not from storage. Always update state in the same function so the interface reacts immediately.
The opposite slip also happens: resetting state but forgetting storage. The app looks logged out, but on the next reload the token is read back and the user is signed in again. Keeping both operations inside one logout function avoids both problems.
Cleaning up cached data
If your app caches user-specific data, such as a cart, a profile or results stored by a data-fetching library, clear that too. Otherwise the next person who logs in on the same browser might briefly see the previous user's data. Also cancel any timer you set for automatic logout, so it does not fire later for a session that no longer exists.
Checklist for a reliable logout
- Remove the token and user details from storage.
- Reset the auth state in context so the UI updates at once.
- Call the server's logout endpoint if it tracks sessions or refresh tokens.
- Navigate to a public route with
replace: true. - Clear cached user data and any auto-logout timer.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.