ReactHooks
useGoogleAuth
Hook that wraps auth.signInWithGoogle for custom Google buttons or flows.
Overview
useGoogleAuth wraps auth.signInWithGoogle for custom buttons or flows. Prefer GoogleButton when you want the branded control.
Install
npx @simpleauthjs/react add google-authUsage
"use client"
import { useGoogleAuth } from "@/components/simpleauth"
export function MyGoogleLogin() {
const { signInWithGoogle, isRedirecting, error } = useGoogleAuth()
return (
<button type="button" disabled={isRedirecting} onClick={() => signInWithGoogle({ redirectUrl: "https://myapp.com/" })}>
{isRedirecting ? "Redirecting…" : "Google"}
</button>
)
}Return value
| Field | Type | Description |
|---|---|---|
signInWithGoogle | (input: { redirectUrl: string }) => void | Starts the redirect flow. |
isRedirecting | boolean | true after click until navigation completes. |
error | string | null | Set when starting the flow throws (e.g. SSR misuse). |
isError | boolean | Convenience flag. |
reset | () => void | Clears local hook state. |
Source
components/simpleauth/hooks/use-google-auth.ts
"use client"
import { useState } from "react"
import { SimpleAuthError } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"
function getErrorMessage(error: unknown) {
if (error instanceof SimpleAuthError) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return "Unable to start Google sign-in."
}
export function useGoogleAuth() {
const auth = useSimpleAuthClient()
const [isRedirecting, setIsRedirecting] = useState(false)
const [error, setError] = useState<string | null>(null)
function signInWithGoogle(input: { redirectUrl: string }) {
setIsRedirecting(true)
setError(null)
try {
auth.signInWithGoogle({ redirectUrl: input.redirectUrl })
} catch (requestError) {
setIsRedirecting(false)
setError(getErrorMessage(requestError))
throw requestError
}
}
function reset() {
setError(null)
setIsRedirecting(false)
}
return {
signInWithGoogle,
isRedirecting,
error,
isError: Boolean(error),
reset,
}
}