Navigation with Expo Router
Complete guide to navigation using Expo Router with typed routes and route groups in Caracal.
Expo Router is a file-based routing library for React Native and web apps built with Expo. It brings the simplicity of file-based routing (like Next.js) to React Native, making navigation intuitive and type-safe.
Overview
Caracal uses Expo Router with the following features enabled:
- Typed Routes: Compile-time route validation and autocomplete
- Route Groups: Organize routes without affecting URL structure
- Deep Linking: Automatic deep link handling
- Shared Routes: Common layouts across multiple screens
- Modal Presentation: Native modal navigation
Key Benefits
- Type-safe navigation: Autocomplete and compile-time errors for route names
- File-based routing: Routes are defined by file structure in
src/app/ - No manual configuration: Router automatically detects screens
- Deep linking by default: Every screen is accessible via URL
Project Structure
Caracal organizes routes using route groups — folders wrapped in parentheses that don't appear in the URL.
src/app/
├── _layout.tsx # Root layout (providers, fonts, route guards)
├── onboarding.tsx # First-launch onboarding (/onboarding)
├── posts/[id].tsx # Signed-in post detail (/posts/1)
├── (auth)/ # Signed-out screens (stack)
│ ├── _layout.tsx
│ ├── login.tsx # Sign in (/login)
│ └── sign-up.tsx # Create account (/sign-up)
└── (home)/ # Signed-in app (native tabs)
├── _layout.tsx # NativeTabs: Home, Profile, Settings
├── index.tsx # Home tab (/)
├── profile.tsx # Profile tab (/profile)
└── settings.tsx # Settings tab (/settings)Route Groups Explained
The root layout shows exactly one of three areas, chosen by Stack.Protected guards:
onboarding: visible only on first launch (useIsFirstTime()).(auth)group: visible while signed out. Holds Sign in and Create account.(home)group: visible while signed in. Holds the three tabs.posts/[id]: shares the signed-in guard with the tabs. Tapping a Home feed card pushes its detail onto the root stack. The header and article scroll together. During iOS pull-down, the gradient stretches from the top edge to follow the header content, then springs back with the scroll view. On native, the title, tags, likes and views each move to their own position using tags scoped to the post ID. The title keeps the same typography in both layouts. The two-line preview has its own shared tag and fades into the full article text as it moves. Going back returns to the same feed, including its filters and scroll position.
The guard values come from the pure function getRouteGuards({ isFirstTime, status }) in src/lib/navigation/route-guards.ts, which has unit tests.
Route groups (folders with parentheses) organize your code without affecting URLs, so (home)/index.tsx is served at / and (auth)/login.tsx at /login.
Root Layout
The root layout (src/app/_layout.tsx) wraps the entire app with providers and configures global navigation settings.
Key responsibilities:
- Provider hierarchy (Theme, HeroUI, API, Keyboard, etc.)
- Splash screen handling
- Font loading
- Global navigation configuration
- Status bar styling
Tab Navigation
The (home) group uses NativeTabs from expo-router/native-tabs, so iOS 26 renders the system liquid glass tab bar.
Tabs:
- Home (
index.tsx): posts feed with search and tag filters - Profile (
profile.tsx): the signed-in account - Settings (
settings.tsx): language, theme, links and logout
Each NativeTabs.Trigger sets a translated NativeTabs.Trigger.Label, an SF Symbol / Material icon, and a translated accessibilityLabel. Pass the label explicitly: without it, VoiceOver keeps the tab names from the first language after the user switches language.
Stack Navigation
The (auth) group uses a plain Stack (headers hidden) so Sign in and Create account can push and go back.
To try the Reanimated shared element transition, open Sign in, tap Create an account, then use the back button. On iOS and Android the Caracal icon moves from the left header into the wider badge on the right. The auth stack activates a shared transition boundary for the focused screen. Both headers render AuthBrandMark with the same sharedTransitionTag. The badge changes width during the 450 ms transition, keeping the Caracal icon visible in both directions. Web renders the two headers with ordinary navigation.
Stack Features:
- Back navigation with native transitions
- Custom headers with
headerShown,headerTitle, etc. - Modal presentation with
presentation: 'modal' - Card animations and gestures
Typed Routes
Caracal has typed routes enabled in app.config.ts:
experiments: {
typedRoutes: true,
}This generates TypeScript types for all routes, providing autocomplete and compile-time validation.
Navigation with Type Safety
import { router } from 'expo-router';
// ✅ Type-safe navigation (autocomplete works)
router.push('/(home)/settings');
router.push('/(home)/profile');
router.navigate('/onboarding');
// ❌ Compile error: route doesn't exist
router.push('/non-existent-route'); // TypeScript error
// Dynamic routes with params
router.push({
pathname: '/posts/[id]',
params: { id: '1' }
});Link Component
import { Link } from 'expo-router';
export function MyComponent() {
return (
<>
{/* Type-safe href */}
<Link href="/(home)/settings">Go to Settings</Link>
{/* With params */}
<Link
href={{
pathname: '/posts/[id]',
params: { id: '1' }
}}
>
Read post
</Link>
{/* Replace instead of push */}
<Link href="/(home)/" replace>
Reset to Home
</Link>
</>
);
}Navigation Hooks
Expo Router provides several hooks for navigation and route information.
useRouter
Imperative navigation API.
import { useRouter } from 'expo-router';
export function MyScreen() {
const router = useRouter();
return (
<Button
onPress={() => {
// Push new screen
router.push('/(home)/settings');
// Navigate (replace if already in stack)
router.navigate('/onboarding');
// Go back
router.back();
// Replace current screen
router.replace('/(home)/');
// Dismiss modal
router.dismiss();
// Can go back?
if (router.canGoBack()) {
router.back();
}
}}
>
Navigate
</Button>
);
}usePathname
Get the current pathname.
import { usePathname } from 'expo-router';
export function MyComponent() {
const pathname = usePathname();
console.log(pathname); // "/settings" or "/posts/1"
return <Text>Current path: {pathname}</Text>;
}useSegments
Get route segments as an array.
import { useSegments } from 'expo-router';
export function MyComponent() {
const segments = useSegments();
console.log(segments); // ["(home)", "settings"] or ["posts", "[id]"]
const isPost = segments[0] === 'posts';
return <Text>Section: {isPost ? 'Posts' : 'App'}</Text>;
}useLocalSearchParams & useGlobalSearchParams
Access route parameters.
import { useLocalSearchParams, useGlobalSearchParams } from 'expo-router';
export function PostDetails() {
// Local params (from this route only)
const local = useLocalSearchParams<{ id: string }>();
// Global params (from entire URL)
const global = useGlobalSearchParams<{ theme?: string }>();
return (
<View>
<Text>Post ID: {local.id}</Text>
<Text>Theme: {global.theme || 'default'}</Text>
</View>
);
}useFocusEffect
Run side effects when screen focuses/unfocuses.
import { useFocusEffect } from 'expo-router';
import { useCallback } from 'react';
export function MyScreen() {
useFocusEffect(
useCallback(() => {
// Screen focused - fetch fresh data
console.log('Screen focused');
return () => {
// Screen unfocused - cleanup
console.log('Screen unfocused');
};
}, [])
);
return <View>...</View>;
}Deep Linking
Every route in Expo Router is automatically deep-linkable. No configuration required.
URL Schemes
The app’s custom scheme comes from Env.SCHEME in app.config.ts. With the template configuration, open caracalApp://settings for Settings or caracalApp://posts/1 for the first post. Both require a signed-in account.
Testing Deep Links
iOS Simulator:
xcrun simctl openurl booted "caracalApp://settings"Android Emulator:
adb shell am start -W -a android.intent.action.VIEW -d "caracalApp://settings"Run these commands against an installed development build.
Handling Deep Links
import { useEffect } from 'react';
import * as Linking from 'expo-linking';
export function useDeepLinkHandler() {
useEffect(() => {
// Get initial URL (app opened from deep link)
Linking.getInitialURL().then((url) => {
if (url) {
console.log('App opened with:', url);
// Handle deep link
}
});
// Listen for deep links while app is running
const subscription = Linking.addEventListener('url', ({ url }) => {
console.log('Deep link received:', url);
// Handle deep link
});
return () => subscription.remove();
}, []);
}With Expo Router, you typically don't need to manually parse deep links. The router automatically navigates to the correct screen based on the URL.
Modal Presentation
Present screens as modals using the presentation option.
Stack Modal
// src/app/(home)/_layout.tsx
<Stack.Screen
name="modal-screen"
options={{
presentation: 'modal',
headerShown: true,
headerTitle: 'Modal Screen',
}}
/>Programmatic Modal
import { router } from 'expo-router';
export function MyComponent() {
return (
<Button
onPress={() => {
router.push({
pathname: '/modal-screen',
});
}}
>
Open Modal
</Button>
);
}
// In modal screen
export function ModalScreen() {
const router = useRouter();
return (
<View>
<Button onPress={() => router.dismiss()}>
Close Modal
</Button>
</View>
);
}Full Screen Modal
<Stack.Screen
name="full-screen-modal"
options={{
presentation: 'fullScreenModal',
headerShown: false,
}}
/>Navigation Guards
Screens are protected with Stack.Protected in src/app/_layout.tsx. Auth is hydrated synchronously from MMKV at module scope, so the first render already knows the status and no redirect flashes.
// src/app/_layout.tsx
hydrateAuth();
export default function RootLayout() {
const status = useAuth((state) => state.status);
const [isFirstTime] = useIsFirstTime();
const guards = getRouteGuards({ isFirstTime, status });
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Protected
guard={guards.canSeeOnboarding}
redirectTo={guards.redirectTo}
>
<Stack.Screen name="onboarding" />
</Stack.Protected>
<Stack.Protected guard={guards.canSeeAuth} redirectTo={guards.redirectTo}>
<Stack.Screen name="(auth)" />
</Stack.Protected>
<Stack.Protected guard={guards.canSeeApp} redirectTo={guards.redirectTo}>
<Stack.Screen name="(home)" />
<Stack.Screen name="posts/[id]" />
</Stack.Protected>
</Stack>
);
}Signing in or out only changes the auth store; the guards then move the user to the right group, so screens never call router.replace after authentication.
Each guard sets redirectTo to the entry screen for the current state: /onboarding on first launch, / when signed in, and /login otherwise. Without it, Expo Router 58 sends a guarded route to the first unguarded route in file order. In this app that route is not a real screen, so the user lands on the not-found screen.
Common Patterns
Back Navigation with Fallback
import { router } from 'expo-router';
function handleBack() {
if (router.canGoBack()) {
router.back();
} else {
router.replace('/(home)/');
}
}Conditional Navigation
function handleLogin() {
if (isFirstTimeUser) {
router.replace('/onboarding');
} else {
router.replace('/(home)/');
}
}Reset Navigation Stack
// Clear stack and go to home
router.dismissAll();
router.replace('/(home)/');Passing Data Between Screens
Via URL params
router.push({ pathname: '/posts/[id]', params: { id: '1' } });
// Inside src/app/posts/[id].tsx
const { id } = useLocalSearchParams<{ id: string }>();Via global state (for complex data):
// Use Zustand
const { setSelectedItem } = useStore();
function handleNavigate(item: Item) {
setSelectedItem(item);
router.push('/item-details');
}Tab Bar Customization
The three tab labels and icons are configured on NativeTabs.Trigger in src/app/(home)/_layout.tsx. To open a detail screen outside the tab bar, follow the signed-in posts/[id] route in the root stack.
Header Customization
<Stack.Screen
name="settings"
options={{
headerShown: true,
headerTitle: 'Settings',
headerTitleAlign: 'center',
headerStyle: {
backgroundColor: '#f5f5f5',
},
headerTintColor: '#000',
headerShadowVisible: false,
headerBackTitle: 'Back',
}}
/>Custom Header Component
<Stack.Screen
name="profile"
options={{
header: () => <CustomHeader />,
}}
/>Troubleshooting
Routes Not Appearing
Problem: New screen not showing in app.
Solution:
- Ensure file is in
src/app/directory - File must export default component
- Restart dev server (
pnpm startthenr) - Clear Metro cache:
pnpm start --clear
Type Errors on Routes
Problem: TypeScript errors on route names.
Solution:
- Types generate on save — edit any file in
src/app/ - Restart TypeScript server in VS Code
- Check
expo-env.d.tsis in your project root
Deep Links Not Working
Problem: Deep links not opening app.
Solution:
- Ensure
schemeis configured inapp.config.ts - Rebuild app after config changes:
pnpm prebuild - Test with correct scheme:
caracalApp://(nothttp://) - Check URL format matches file structure
Tab Bar Flickering
Problem: Tab bar flickers when navigating.
Solution:
<Tabs
screenOptions={{
lazy: false, // Render all tabs immediately
}}
>
{/* tabs */}
</Tabs>Best Practices
- Use typed routes: Always use TypeScript autocomplete for route names
- Route groups: Organize related screens in route groups
- Lazy loading: Use
lazy: truefor tabs with heavy content - Deep link testing: Test all routes with deep links in development
- Navigation guards: Protect authenticated routes at root layout
- Error boundaries: Add error boundaries to catch navigation errors
- Back button: Always provide a way to go back (header or custom button)
- Modal dismissal: Ensure modals can be dismissed with gestures or button