What is the useSession hook in NextAuth?
useSession() from next-auth/react is a client-side hook that returns the current session and its loading status: { data, status, update }, where status is "loading", "authenticated" or "unauthenticated". It requires a <SessionProvider> in a Client Component above it.
Usage
- Wrap the app in
<SessionProvider>(a Client Component) in the root layout. Pass the server-fetched session as a prop to avoid an initial loading state. const { data: session, status } = useSession()in any Client Component.useSession({ required: true, onUnauthenticated() { ... } })redirects when signed out.update(data)refreshes the session, for example after the user changes their name.
How it works
It fetches /api/auth/session and caches the result in the provider. It refetches when the window regains focus and optionally on an interval (refetchInterval).
When to use it
- Showing the user's avatar or name in client-side UI.
- Toggling client-only features.
When not to
- Protecting data: client checks are cosmetic. Data must be protected on the server.
- Server Components: use
await auth()instead; it needs no extra request and no loading state.
Interview point
In the App Router, prefer reading the session on the server and passing what the client needs as props. Use useSession only where client components need to react to session changes.
Code example
1// app/providers.tsx2"use client";3import { SessionProvider } from "next-auth/react";4import type { Session } from "next-auth";56export function Providers({ session, children }: { session: Session | null; children: React.ReactNode }) {7 return <SessionProvider session={session}>{children}</SessionProvider>;8}910// app/components/user-menu.tsx11"use client";12import { useSession, signOut } from "next-auth/react";1314export function UserMenu() {15 const { data: session, status } = useSession();1617 if (status === "loading") return <span>…</span>;18 if (!session) return <a href="/api/auth/signin">Sign in</a>;1920 return (21 <div>22 <img src={session.user?.image ?? ""} alt="" width={24} height={24} />23 {session.user?.name}24 <button onClick={() => signOut()}>Sign out</button>25 </div>26 );27}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.