πŸ‘€ See Sanity in action: Watch product demo now β†’

useCurrentUser Custom React Hook

By Simeon Griggs

Get details of the currently logged in Sanity user

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

πŸ‡¦πŸ‡Ί in πŸ‡¬πŸ‡§ Solution Engineer @ Sanity

Simeon is located at Newcastle upon Tyne, UK
Visit Simeon Griggs's profile

Other schemas by author