Skip to main content

Lesson 2 of 9

Context API + useReducer - Auth Pattern

Context + useReducer is the right pattern for auth state: it's globally accessible, the transitions are explicit (LOGIN / LOGOUT / UPDATE_PROFILE), and it integrates naturally with SecureStore for token persistence.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Auth Context with SecureStore

Auth Context with SecureStore
import { createContext, useContext, useReducer, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';

// ---- Types ----
interface User { id: string; name: string; email: string; avatarUri?: string; }

interface AuthState {
  user: User | null;
  token: string | null;
  isLoading: boolean;
}

type AuthAction =
  | { type: 'RESTORE_TOKEN'; token: string; user: User }
  | { type: 'SIGN_IN'; token: string; user: User }
  | { type: 'SIGN_OUT' }
  | { type: 'UPDATE_USER'; user: Partial<User> }
  | { type: 'LOADING_DONE' };

function authReducer(state: AuthState, action: AuthAction): AuthState {
  switch (action.type) {
    case 'RESTORE_TOKEN': return { ...state, token: action.token, user: action.user, isLoading: false };
    case 'SIGN_IN': return { ...state, token: action.token, user: action.user };
    case 'SIGN_OUT': return { ...state, token: null, user: null };
    case 'UPDATE_USER': return { ...state, user: state.user ? { ...state.user, ...action.user } : null };
    case 'LOADING_DONE': return { ...state, isLoading: false };
    default: return state;
  }
}

// Split context: stable dispatch vs frequently-changing state
const AuthStateCtx = createContext<AuthState | null>(null);
const AuthDispatchCtx = createContext<React.Dispatch<AuthAction> | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(authReducer, { user: null, token: null, isLoading: true });

  // Restore token from SecureStore on app start
  useEffect(() => {
    Promise.all([
      SecureStore.getItemAsync('access_token'),
      SecureStore.getItemAsync('user_data'),
    ]).then(([token, userData]) => {
      if (token && userData) {
        dispatch({ type: 'RESTORE_TOKEN', token, user: JSON.parse(userData) });
      } else {
        dispatch({ type: 'LOADING_DONE' });
      }
    });
  }, []);

  return (
    <AuthStateCtx.Provider value={state}>
      <AuthDispatchCtx.Provider value={dispatch}>
        {children}
      </AuthDispatchCtx.Provider>
    </AuthStateCtx.Provider>
  );
}

// Hooks - typed access
export const useAuthState = () => {
  const ctx = useContext(AuthStateCtx);
  if (!ctx) throw new Error('useAuthState must be inside AuthProvider');
  return ctx;
};

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

// Convenience action creators
export async function signIn(dispatch: React.Dispatch<AuthAction>, token: string, user: User) {
  await Promise.all([
    SecureStore.setItemAsync('access_token', token),
    SecureStore.setItemAsync('user_data', JSON.stringify(user)),
  ]);
  dispatch({ type: 'SIGN_IN', token, user });
}

export async function signOut(dispatch: React.Dispatch<AuthAction>) {
  await Promise.all([
    SecureStore.deleteItemAsync('access_token'),
    SecureStore.deleteItemAsync('user_data'),
  ]);
  dispatch({ type: 'SIGN_OUT' });
}

Tip

Tip

Practice Context API useReducer Auth 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โ€ฆ

Distributing authentication state and theme tokens with React Context

Practice Task

Note

Practice Task - (1) Write a working example of Context API useReducer Auth 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 Context API useReducer Auth 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.

Topics in This Module

0/9 done