SimpleAuth
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

NameTypeDefaultDescription
autoLoadbooleantrueWhen true, calls refresh() once on mount.

Returns

FieldTypeDescription
refresh() => Promise<MeResponse>Loads the current user again.
dataMeResponse | nullLast successful response from me().
errorstring | nullHuman-readable error string when the request fails.
isErrorbooleanConvenience flag derived from error.
isLoadingbooleanTrue 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 SimpleAuthProvider via useSimpleAuthClient.
  • Normalizes failures with SimpleAuthError when the SDK throws.
  • Swallows the initial load error in useEffect so your UI can decide how to surface it.

Shipped by

npx @simpleauthjs/react init

Source

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,
  }
}

On this page