Logout
- React Native course
- Advanced
- Lesson 47/83
- 5 min
Learn logout and token cleanup.
Logout
Logout is the user signing out of the app. Two things happen: the token is deleted and the user state is set to null. With SecureStore.deleteItemAsync('token') the token is removed from the device; setUser(null) resets the auth context.
Then the user is navigated to the login screen. navigation.replace('Login') is preferred; this way the back button cannot return to protected screens. When the logout button is pressed handleLogout runs; this function must be async.
Delete the token from secure storage
During logout the device token is also deleted. With await SecureStore.deleteItemAsync('token') it is removed from the secure store. This call is asynchronous so handleLogout must be async. Even if deletion fails setUser(null) is called; the user is still redirected to login.
The logout function is usually defined as a logout action on the auth context. Components get it with const { logout } = useContext(AuthContext) and call it on button press. This keeps logout logic in one place.
Practice Write handleLogout
Complete the handleLogout function. Delete the token with await SecureStore.deleteItemAsync('token'). Then call setUser(null).
Starter code
import * as SecureStore from 'expo-secure-store';
export function makeLogout(setUser) {
async function handleLogout() {
// delete the token, reset the user
}
return { handleLogout };
}Sample solution
import * as SecureStore from 'expo-secure-store';
export function makeLogout(setUser) {
async function handleLogout() {
await SecureStore.deleteItemAsync('token');
setUser(null);
}
return { handleLogout };
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does logout call setUser(null)?
- To repaint the screen
- To change styles
- To speed up animation
- To reset the auth context Correct answer
Explanation: setUser(null) resets the auth context.
2 Reset the user
function logout() {
setUser(____);
}
function logout() {
setUser(null);
}
Explanation: Write null; this is the empty state of the auth context.
3 Match the logout parts
| Term | Meaning |
|---|---|
deleteItemAsync |
Deletes the token |
setUser(null) |
Resets the context |
navigation.replace |
Jumps to Login |
async |
Requires await |