Skip to main content

Lesson 8 of 10

Authentication Flow Pattern

The authentication flow is one of the most error-prone parts of navigation. The pattern is: conditional rendering of Auth stack vs Main stack based on auth state - NOT manual navigation.navigate('Login').

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Auth-Aware Navigation

Auth-Aware Navigation
// ---- Auth Context ----
import { createContext, useContext, useState, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';

interface AuthState {
  token: string | null;
  isLoading: boolean;
  signIn: (token: string) => Promise<void>;
  signOut: () => Promise<void>;
}

const AuthContext = createContext<AuthState | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Restore token from secure storage on app start
    SecureStore.getItemAsync('access_token').then(t => {
      setToken(t);
      setIsLoading(false);
    });
  }, []);

  async function signIn(newToken: string) {
    await SecureStore.setItemAsync('access_token', newToken);
    setToken(newToken);
    // Navigation handles itself - no navigation.navigate() call needed
  }

  async function signOut() {
    await SecureStore.deleteItemAsync('access_token');
    setToken(null);
    // Navigator automatically shows Auth stack when token is null
  }

  return (
    <AuthContext.Provider value={{ token, isLoading, signIn, signOut }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be inside AuthProvider');
  return ctx;
};

// ---- Root navigator - conditional based on auth ----
function RootNavigator() {
  const { token, isLoading } = useAuth();

  if (isLoading) return <SplashScreen />; // while checking secure storage

  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      {token ? (
        // User is logged in → show main app
        <Stack.Screen name="Main" component={MainTabNavigator} />
      ) : (
        // User is not logged in → show auth screens
        // Note: 'Auth' group uses a DIFFERENT Stack so history is clean
        <Stack.Screen name="Auth" component={AuthStackNavigator} />
      )}
    </Stack.Navigator>
  );
  // When signIn/signOut runs, token changes → navigator re-renders
  // The correct stack is shown automatically with NO navigation.navigate() code
}

function SplashScreen() {
  return <View style={{ flex: 1, backgroundColor: '#0f172a' }} />;
}
function MainTabNavigator() { return null; }
function AuthStackNavigator() { return null; }

Common Mistakes

  • Calling `navigation.navigate('Login')` after logout - the conditional navigator pattern means you should never navigate to auth screens manually. Simply clear the token and the navigator handles it
  • Not wrapping `NavigationContainer` with `GestureHandlerRootView` - swipe back on iOS and drawer gestures silently stop working on RN CLI if GestureHandlerRootView is missing
  • Putting tab-level headers inside individual screens - let the Tab.Navigator's screenOptions control the shared header; per-screen overrides go in `options`
  • Not handling the Android hardware back button - React Navigation handles it by default, but `navigation.addListener('beforeRemove')` is needed for back-press confirmation dialogs (file upload, unsaved form)

Tip

Tip

Practice Authentication Flow Pattern in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Seamless conditional screen switching between Auth and App stacks

Practice Task

Note

Practice Task - (1) Write a working example of Authentication Flow Pattern from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Authentication Flow Pattern is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Key Takeaways

  • The authentication flow is one of the most error-prone parts of navigation.
  • Calling `navigation.navigate('Login')` after logout - the conditional navigator pattern means you should never navigate to auth screens manually. Simply clear the token and the navigator handles it
  • Not wrapping `NavigationContainer` with `GestureHandlerRootView` - swipe back on iOS and drawer gestures silently stop working on RN CLI if GestureHandlerRootView is missing
  • Putting tab-level headers inside individual screens - let the Tab.Navigator's screenOptions control the shared header; per-screen overrides go in `options`

Topics in This Module

0/10 done