Skip to Content

useSession

Hook that returns the signed-in user and a hasRole function for role checks. The component re-renders on every sign-in and sign-out.

Usage

app/components/user-menu.tsx
import { Button, Space } from "antd"; import { useNavigate } from "react-router-dom"; import { useSession } from "app/hooks"; export function UserMenu() { const { user, hasRole, signOut } = useSession(); const nav = useNavigate(); if (!user) return <Button onClick={() => nav("/login")}>Sign in</Button>; return ( <Space> {user.name} {hasRole("owner", "manager") && <Button onClick={() => nav("/reports")}>Reports</Button>} <Button onClick={() => { signOut(); nav("/login"); }}>Sign out</Button> </Space> ); }

Signature

app/hooks.ts
type SessionUser = { id: number; name: string; email: string; role: string; avatarUrl?: string | null }; function useSession(): { user: SessionUser | null; signIn: typeof signIn; signOut: typeof signOut; hasRole: (...roles: string[]) => boolean; };

Parameters

None.

Returns

  • user: the signed-in user, or null when nobody is signed in. The value comes from the latest signIn.
  • hasRole(...roles): true when someone is signed in and their role is in the list.
  • signIn, signOut: the same signIn and signOut functions.

The hook also picks up sign-ins and sign-outs in other tabs of the same browser.

Examples

Hide a button from users without the right role:

app/orders/page.tsx
const { hasRole } = useSession(); {hasRole("owner") && <Button danger>Delete order</Button>}

Hiding a button only changes the UI. The API still has to block the call with access in the handler, see Sign-in and permissions.

Next steps

Last updated