For managing authentication state globally in a React application, wrap your app in an AuthProvider using React Context. This pattern allows you to initialize authentication, check for existing users, and handle token expiration automatically on app startup.
Key methods to include in your context:
signIn(): Triggers the sign-in flow.signOut(): Clears the user session.refreshTokens(): Manually refreshes the current tokens.getCurrentUser(): Retrieves the currently authenticated user.isTokenExpired(): Checks if the current token is no longer valid.
import React, { createContext, useContext, useEffect, useState } from 'react';
import { GoogleAuth } from 'react-native-google-auth';
const AuthContext = createContext(undefined);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const initializeAuth = async () => {
try {
await GoogleAuth.configure({
iosClientId: 'YOUR_IOS_CLIENT_ID',
androidClientId: 'YOUR_ANDROID_CLIENT_ID'
});
const currentUser = await GoogleAuth.getCurrentUser();
if (currentUser) {
const isExpired = await GoogleAuth.isTokenExpired();
if (isExpired) {
await GoogleAuth.refreshTokens();
}
setUser(currentUser);
}
} catch (error) {
console.log('Auth initialization failed', error);
} finally {
setIsLoading(false);
}
};
initializeAuth();
}, []);
// ... signIn, signOut, refreshTokens implementations
return (
<AuthContext.Provider value={{ user, isLoading, signIn, signOut, refreshTokens }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);