Protect content and read user data
Clerk provides a set of hooks that you can use to protect content and read user data in your React application. Here are examples of how to use these hooks to get you started.
useAuth()
The following example uses the useAuth() hook to access the current auth state, as well as helper methods to manage the current session.
export default function Example() {
const { isLoaded, isSignedIn, userId, sessionId, getToken } = useAuth()
const fetchExternalData = async () => {
// Use `getToken()` to get the current user's session token
const token = await getToken()
// Use `token` to fetch data from an external API
const response = await fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${token}`,
},
})
return response.json()
}
// Use `isLoaded` to check if Clerk is loaded
if (!isLoaded) {
return <div>Loading...</div>
}
// Use `isSignedIn` to check if the user is signed in
if (!isSignedIn) {
// You could also add a redirect to the sign-in page here
return <div>Sign in to view this page</div>
}
return (
<div>
Hello, {userId}! Your current active session is {sessionId}.
</div>
)
}useUser()
The following example demonstrates how to use the useUser() hook to access the User object, which contains the current user's data such as their ID.
import { useUser } from '@clerk/react'
export default function Example() {
const { isSignedIn, user, isLoaded } = useUser()
// Handle loading state
if (!isLoaded) return <div>Loading...</div>
// Protect the page from unauthenticated users
if (!isSignedIn) return <div>Sign in to view this page</div>
return <div>Hello {user.id}!</div>
}Protect content and read user data
Learn how to use Clerk's hooks to protect content and read user data in your React app.
Prebuilt components
Learn how to quickly add authentication to your app using Clerk's suite of components.
Customization & localization
Learn how to customize and localize the Clerk components.
Clerk React SDK Reference
Learn about the Clerk React SDK and how to integrate it into your app.
Feedback
Last updated on