Joint session with Vercel: How to build intelligent storefronts (May 15th)

useCurrentUser Custom React Hook

Get details of the currently logged in Sanity user

By Simeon Griggs


getCurrentUser.js

// You may not need this snippet!

// 1. The Studio exports its own version of this hook
import { useCurrentUser } from "@sanity/base/hooks";


// 2. OR, you can DIY it if you'd prefer
import userStore from 'part:@sanity/base/user'
import { useEffect, useState } from 'react'

export function useCurrentUser() {
  const [user, setUser] = useState({})

  useEffect(() => {
    userStore.currentUser.subscribe(e => setUser(e.user))
  }, [])

  return user
}

Sometimes you want to gate or modify your custom Studio components based on the current logged in user.

The Studio exports a version of this hook. Or you could use the snippet to create your own. Use either to get the current user's ID, email address, and more.

Contributor

Simeon Griggs

Customer Education at Sanity

Visit Simeon Griggs's profile