I want to add a view with the Structure builder (S.view.component) where I list similar documents based on the title. What would be the best way to use GROQ there?

7 repliesLast updated: Nov 29, 2025

Hi! I want to add a view with the Structure builder (
S.view.component
) where I list similar documents based on the title. What would be the best way to use GROQ there? Should I use the
documentStore
, or is there an easier way?
AI Update

For creating a custom view with S.view.component() that displays similar documents based on title, you have a couple of good options for querying data with GROQ:

The easiest approach is to use the useClient hook from the sanity package. This hook provides a configured Sanity client that's ready to use in your component:

import { useClient } from 'sanity'
import { useEffect, useState } from 'react'

function SimilarDocumentsView(props) {
  const client = useClient({apiVersion: '2024-01-01'})
  const [similarDocs, setSimilarDocs] = useState([])
  const { documentId, document } = props

  useEffect(() => {
    if (!document?.title) return
    
    const query = `*[_type == $type && _id != $id && title match $title][0...5] {
      _id,
      title,
      _type
    }`
    
    client.fetch(query, {
      type: document._type,
      id: documentId,
      title: `${document.title}*`
    }).then(setSimilarDocs)
  }, [client, documentId, document?.title])

  return (
    <div>
      <h2>Similar Documents</h2>
      {similarDocs.map(doc => (
        <div key={doc._id}>{doc.title}</div>
      ))}
    </div>
  )
}

The useClient hook is simpler than working with documentStore directly and gives you a fully configured client for making GROQ queries.

Alternative: Using documentStore

While you could use the documentStore from the Studio's context, it's generally more complex and intended for lower-level document operations. The useClient hook abstracts away that complexity and is the recommended approach for custom views.

Props Available in Custom Views

Your custom view component receives useful props including:

Structure Builder Setup

In your Structure Builder configuration:

S.view
  .component(SimilarDocumentsView)
  .title('Similar Documents')

The useClient approach is cleaner, more maintainable, and follows current Sanity Studio v3 best practices for custom document views.

Show original thread
7 replies

Was this answer helpful?

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Related contributions