Protected routes
- React Native course
- Advanced
- Lesson 46/83
- 5 min
Learn protected routes and navigation guards.
Protected route
A protected route is a screen that only signed-in users can see. If the user is not signed in they are redirected to the login screen. To do this you run a guard check on the screen: if (!user) return <Navigate to='Login' />.
With React Navigation this is done with useEffect and useNavigation. When the screen opens the user is checked; if missing navigation.replace('Login') is called. This keeps protected content invisible to signed-out users.
Navigation guard
The guard is written inside a useEffect that runs when the screen opens. The dependency array should contain user; so the check runs again when the user changes. An empty array runs it only once on open.
Inside you write if (!user) navigation.replace('Login'). replace prevents the back button from going back to Login; it is preferred over navigate. This way pressing back exits the app; it does not return to Login.
Practice Write a ProtectedScreen
Complete the ProtectedScreen component. Get user with useContext(AuthContext). Inside useEffect write if (!user) navigation.replace('Login'). The useEffect dependency array should contain user.
Starter code
import React, { useContext, useEffect } from 'react';
import { Text, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { AuthContext } from './AuthContext';
export function ProtectedScreen() {
const { user } = useContext(AuthContext);
const navigation = useNavigation();
// write the guard
return (
<View>
<Text>Welcome</Text>
</View>
);
}Sample solution
import React, { useContext, useEffect } from 'react';
import { Text, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { AuthContext } from './AuthContext';
export function ProtectedScreen() {
const { user } = useContext(AuthContext);
const navigation = useNavigation();
useEffect(() => {
if (!user) navigation.replace('Login');
}, [user]);
return (
<View>
<Text>Welcome</Text>
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the guard parts
| Term | Meaning |
|---|---|
useEffect |
Runs the check on open |
useNavigation |
Provides navigation |
navigation.replace |
Jumps to Login |
AuthContext |
Provides the user |
2 The redirect call
if (!user) {
navigation.____('Login');
}
if (!user) {
navigation.replace('Login');
}
Explanation: replace blocks the back button.
3 Why does the guard prefer replace?
- To block the back button from returning to Login
- For faster animation
- To change styles Correct answer
- For less memory
Explanation: replace blocks the back button from returning to Login.