Performance: Client-side session access
This affects page load speed and interaction responsiveness by how session data is accessed and rendered on the client side.
Jump into concepts and practice - no test required
import { useSession } from 'next-auth/react'; export default function Profile() { const { data: session } = useSession({ required: false }); return <p>Welcome, {session?.user?.name ?? 'Guest'}</p>; }
import { useSession } from 'next-auth/react'; export default function Profile() { const { data: session, status } = useSession(); if (status === 'loading') return <p>Loading...</p>; return <p>Welcome, {session.user.name}</p>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking session fetch with loading UI | Moderate (conditional DOM nodes) | Multiple reflows due to content shift | High paint cost on update | [X] Bad |
| Non-blocking session fetch with fallback UI | Low (static DOM initially) | Single reflow on update | Low paint cost | [OK] Good |
useSession hook from next-auth provide in a Next.js app?useSessionuseSession hook is designed to provide session data and status on the client side in Next.js apps using next-auth.useSession in a Next.js component?useSession in next-auth v4+ is from 'next-auth/react'. The hook returns an object with data and status.data as session. Other options use wrong import paths or incorrect usage.useSession:
import { useSession } from 'next-auth/react';
export default function Profile() {
const { data: session, status } = useSession();
if (status === 'loading') return <p>Loading...</p>;
if (!session) return <p>Not signed in</p>;
return <p>Welcome, {session.user.name}!</p>;
}
What will be rendered if the user is signed in with name "Alex"?session exists and status is not 'loading'. So it renders the welcome message with the user's name.useSession:
import { useSession } from 'next-auth/react';
export default function Dashboard() {
const session = useSession();
if (session.status === 'loading') return <p>Loading...</p>;
if (!session.data) return <p>Please sign in</p>;
return <p>Hello, {session.user.name}</p>;
}useSession returns an object with data and status. The user info is inside data.user.session.user.name directly, but it should be session.data.user.name. This causes an error.useSession returns { data: session, status }, which code snippet correctly implements this in a Next.js component?status === 'loading' first to avoid rendering before session is ready.session exists and if session.user.emailVerified is true. If not, show the verification message.