ReactHooks
useCurrentUser
Fetch and refresh the current session user from the SimpleAuth browser client.
Overview
useCurrentUser wraps auth.me() from @simpleauthjs/core. It tracks loading and error state, optionally loads on mount, and exposes a manual refresh function.
Signature
export function useCurrentUser(options: UseCurrentUserOptions = {})Where UseCurrentUserOptions is { autoLoad?: boolean }.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
autoLoad | boolean | true | When true, calls refresh() once on mount. |
Returns
| Field | Type | Description |
|---|---|---|
refresh | () => Promise<MeResponse> | Loads the current user again. |
data | MeResponse | null | Last successful response from me(). |
error | string | null | Human-readable error string when the request fails. |
isError | boolean | Convenience flag derived from error. |
isLoading | boolean | True while a request is in flight. |
Example
"use client"
import { useCurrentUser } from "@/components/simpleauth"
export function ProfileBadge() {
const { data, isLoading, error, refresh } = useCurrentUser()
if (isLoading) return <span>Loading…</span>
if (error) return <button type="button" onClick={() => refresh()}>Retry</button>
if (!data?.user) return <span>Signed out</span>
return <span>{data.user.email}</span>
}How it works
- Reads the shared client from
SimpleAuthProviderviauseSimpleAuthClient. - Normalizes failures with
SimpleAuthErrorwhen the SDK throws. - Swallows the initial load error in
useEffectso your UI can decide how to surface it.
Shipped by
npx @simpleauthjs/react initSource
components/simpleauth/hooks/use-current-user.ts
"use client"
import { useCallback, useEffect, useState } from "react"
import { SimpleAuthError, type MeResponse } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"
type UseCurrentUserOptions = {
autoLoad?: boolean
}
function getErrorMessage(error: unknown) {
if (error instanceof SimpleAuthError) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return "Unable to fetch current user."
}
export function useCurrentUser(options: UseCurrentUserOptions = {}) {
const { autoLoad = true } = options
const auth = useSimpleAuthClient()
const [isLoading, setIsLoading] = useState(Boolean(autoLoad))
const [error, setError] = useState<string | null>(null)
const [data, setData] = useState<MeResponse | null>(null)
const refresh = useCallback(async () => {
setIsLoading(true)
setError(null)
try {
const response = await auth.me()
setData(response)
return response
} catch (requestError) {
setData(null)
setError(getErrorMessage(requestError))
throw requestError
} finally {
setIsLoading(false)
}
}, [auth])
useEffect(() => {
if (!autoLoad) {
return
}
refresh().catch(() => {})
}, [autoLoad, refresh])
return {
refresh,
data,
error,
isError: Boolean(error),
isLoading,
}
}