The preferred way to use this hook when working with Sanity Typegen.
Features:
This hook will suspend while the document data is being fetched and loaded.
When fetching a full document:
null
if the document doesn't existWhen fetching with a path:
undefined
if either the document doesn't exist or the path doesn't exist in the documentConfiguration including documentId
, documentType
, and optionally:
path
: To select a nested value (returns typed value at path)projectId
/dataset
: For multi-project/dataset setupsThe document state (or nested value if path provided).
import {useDocument, type DocumentHandle} from '@sanity/sdk-react'
interface ProductViewProps {
doc: DocumentHandle<'product'> // Typegen infers product type
}
function ProductView({doc}: ProductViewProps) {
const {data: product} = useDocument({...doc}) // Fully typed product
return <h1>{product.title ?? 'Untitled'}</h1>
}
import {useDocument, type DocumentHandle} from '@sanity/sdk-react'
interface ProductTitleProps {
doc: DocumentHandle<'product'>
}
function ProductTitle({doc}: ProductTitleProps) {
const {data: title} = useDocument({
...doc,
path: 'title' // Returns just the title field
})
return <h1>{title ?? 'Untitled'}</h1>
}
Use this version when:
Key differences from Typegen version:
TData
TData | null
for full documentsTData | undefined
for nested valuesThis hook will suspend while the document data is being fetched.
The explicit type for the document or field
Optional path to a nested value
Configuration including documentId
and optionally:
path
: To select a nested valueprojectId
/dataset
: For multi-project/dataset setupsThe document state (or nested value if path provided)
import {useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'
interface Book extends SanityDocument {
_type: 'book'
title: string
author: string
}
interface BookViewProps {
doc: DocumentHandle
}
function BookView({doc}: BookViewProps) {
const {data: book} = useDocument<Book>({...doc})
return <h1>{book?.title ?? 'Untitled'} by {book?.author ?? 'Unknown'}</h1>
}
import {useDocument, type DocumentHandle} from '@sanity/sdk-react'
interface BookTitleProps {
doc: DocumentHandle
}
function BookTitle({doc}: BookTitleProps) {
const {data: title} = useDocument<string>({...doc, path: 'title'})
return <h1>{title ?? 'Untitled'}</h1>
}
Reads and subscribes to a document's realtime state, incorporating both local and remote changes.
This hook comes in two main flavors to suit your needs:
Remarks
useDocument
is ideal for realtime editing interfaces where you need immediate feedback on changes. However, it can be resource-intensive since it maintains a realtime connection.For simpler cases where:
…consider using useDocumentProjection or useQuery instead. These hooks are more efficient for read-heavy applications.