SimpleAuth
ReactHooks

useSignOut

End the current session with auth.logout().

Overview

useSignOut wraps auth.logout() with loading, error, and response helpers.

Signature

export function useSignOut()

Parameters

This hook takes no parameters.

Returns

FieldTypeDescription
signOut() => Promise<unknown>Calls auth.logout and updates local state.
dataunknownLast successful response when present.
errorstring | nullHuman-readable error when logout fails.
isErrorbooleanConvenience flag from error.
isLoadingbooleanTrue while the logout request runs.
reset() => voidClears hook state.

Example

"use client"

import { useSignOut } from "@/components/simpleauth"

export function LogoutControl() {
  const { signOut, isLoading, error } = useSignOut()

  return (
    <div>
      <button type="button" onClick={() => void signOut()} disabled={isLoading}>
        {isLoading ? "Signing out…" : "Sign out"}
      </button>
      {error ? <p>{error}</p> : null}
    </div>
  )
}

How it works

  • Uses useSimpleAuthClient(); session cookies are cleared by the API as configured on your backend.

Shipped by

npx @simpleauthjs/react add sign-out

Source

components/simpleauth/hooks/use-sign-out.ts
"use client"

import { useState } from "react"
import { SimpleAuthError, type SuccessResponse } 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 sign out."
}

export function useSignOut() {
  const auth = useSimpleAuthClient()
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [data, setData] = useState<SuccessResponse | null>(null)

  async function signOut() {
    setIsLoading(true)
    setError(null)

    try {
      const response = await auth.logout()
      setData(response)
      return response
    } catch (requestError) {
      setData(null)
      setError(getErrorMessage(requestError))
      throw requestError
    } finally {
      setIsLoading(false)
    }
  }

  function reset() {
    setData(null)
    setError(null)
    setIsLoading(false)
  }

  return {
    signOut,
    data,
    error,
    isError: Boolean(error),
    isLoading,
    reset,
  }
}

On this page