Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

useSession

Access the current Session object inside your components.

Overview

The useSession hook accesses the current user Session object. It can be used to retrieve information about the session status. The useSession hook is a shortcut for retrieving the Clerk.session property.

As soon as a User signs in, we create a Session on the Client object. Only one session can be active on a single client, and that's exactly the session that is returned by the useSession hook.

The Session object returned from the hook will hold all state for the currently active session. As such, the useSession hook must be called from a component that is a descendant of the <SignedIn/> component. Otherwise, the hook will throw an error.

Usage

Typescript

For better type support, we highly recommend updating to at least Typescript 4.6. Applications using Typescript will benefit significantly from Typescript's new Control Flow Analysis for Dependent Parameters when using our hooks.

The following example accesses the Session object in order to display how long a user has been active in this client session. Note that you can also get to the User object through the useSession hook.

1
import { SignedIn, useSession } from "@clerk/clerk-react";
2
3
function App() {
4
return (
5
<SignedIn>
6
<Analytics />
7
</SignedIn>
8
);
9
}
10
11
function Analytics() {
12
const { isLoaded, session } = useSession();
13
14
if (!isLoaded) {
15
// handle loading state
16
return null;
17
}
18
19
return (
20
<div>
21
This session has been active
22
since {session.lastActiveAt}.
23
</div>
24
);
25
}

Was this helpful?

Clerk © 2023