К основному содержанию
скилл CX Codex

sanity-form-component-suspense — скилл для Claude Code

Скилл sanity-form-component-suspense для Claude Code устраняет предупреждения о нехватке границ Suspense в кастомных полях Sanity Studio. Срабатывает при сдвигах вёрстки из-за React.lazy или хуков App SDK.

MIT 271 установок ★ 201 обновлён 2026-10-23

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add sanity-io/agent-toolkit --skill sanity-form-component-suspense -a claude-code
Открыть на GitHub

Что делает sanity-form-component-suspense

Скилл находит кастомные компоненты ввода, полей и элементов списков Sanity Studio, которые асинхронно запрашивают данные и не имеют собственной границы <Suspense>. По умолчанию Studio оборачивает всё поле в универсальный скелетон, из-за чего форма дёргается при загрузке, а в консоль сыплются предупреждения.

Агент выносит асинхронный код с React.lazy, use() или хуками вроде useDocumentProjection в отдельный компонент и задаёт для скелетона точную высоту строки. Вызов props.renderDefault остаётся снаружи границы, поэтому стандартное поле не теряет фокус при повторной загрузке данных.

На ещё не сохранённых документах хуки SDK ждут бесконечно, поэтому скилл добавляет проверку _createdAt через useFormValue. Без этой проверки форма нового документа зависает со скелетоном навсегда.

Какие задачи решает

  • убрать предупреждения консоли о компонентах Sanity Studio без Suspense
  • предотвратить сдвиг интерфейса при асинхронной загрузке полей
  • сохранить фокус ввода при повторной загрузке асинхронных данных
  • починить вечный скелетон на новых несохранённых документах

Примеры запросов агенту

  • Оберни асинхронный селектор в схеме schema/product.ts в собственную границу Suspense
  • Исправь предупреждение консоли о компоненте без Suspense в кастомном поле Sanity
  • Почини зависающий скелетон при создании нового документа в Sanity Studio

Как установить sanity-form-component-suspense

1Через Skills CLI (Vercel)

npx skills add sanity-io/agent-toolkit --skill sanity-form-component-suspense -a claude-code

2Вручную: положить файлы

~/.claude/skills/sanity-form-component-suspense/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/sanity-form-component-suspense/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о sanity-form-component-suspense

Как установить sanity-form-component-suspense в Claude Code?

Выполните команду npx skills add sanity-io/agent-toolkit --skill sanity-form-component-suspense -a claude-code.

Зачем нужен sanity-form-component-suspense?

Он помогает изолировать асинхронные вызовы в формах Sanity Studio, чтобы интерфейс не дёргался при монтировании компонентов.

Что нужно для работы sanity-form-component-suspense?

Скилл работает с кодовой базой Sanity Studio на React, где используются хуки App SDK, React.lazy или функция use().

Исходный текст

SKILL.md · MIT
---
name: sanity-form-component-suspense
description: Fix a Sanity Studio custom form component (components.input, components.field, components.item, or a plugin's form.components) that suspends without its own Suspense boundary, so it loads without layout shift and never blocks new documents. Use when the console warns "The custom input/field/item component ... suspended without a <Suspense> boundary of its own" or "A form component ... suspended without a <Suspense> boundary of its own", when a custom form component uses React.lazy, use(), App SDK hooks (useDocumentProjection, useQuery, useDocument) or another suspending data library, or when a field or array item shows a skeleton that never goes away on new documents.
---

# Custom form components that suspend

Studio puts a fallback boundary around every field and every array item, so one suspending
component cannot blank the form. That fallback is a generic skeleton: it does not know the size of
what it replaces, so the form shifts when the component loads, and Studio warns about it in the
console. The fix always lives in your code: declare a `Suspense` around the part that suspends,
with a fallback that takes the same space as what it stands in for. Any boundary you declare is
closer to what suspends than Studio's, so it always wins and nothing warns. That includes a
boundary in a custom field around `props.renderDefault(props)`, which also covers the field's
input: use it when one fallback should cover both, for example a lazy input that also fetches.

## Workflow

1. **Find the component.** The warning names the custom components declared for that field or
   item (`components.field`, `.input` or `.item`), the path, the document type and the schema type,
   and logs the components themselves; click one in the browser console to open its source.
   Production builds minify the names, so use the path and document type there. When the schema
   type declares none, the warning starts with "A form component" and the culprit is usually a
   plugin's `form.components`. React DevTools' Suspense tab shows which component actually
   suspended.
2. **Find what suspends.** Usually one of: `React.lazy`, `use(promise)`, an App SDK hook
   (`useDocumentProjection`, `useDocument`, `useQuery`, `useDocuments`), or a library in suspense
   mode (`useSuspenseQuery`).
3. **Move it into its own component** if it is not already, and wrap only that component in
   `<Suspense>` inside the custom component. Keep `props.renderDefault(props)` outside the
   boundary, so the built-in input, field or item never unmounts (and never loses focus while
   someone types) when the async part suspends again.
4. **Reserve the space.** The fallback must have the size of the loaded UI:
   - Additive UI (warnings, previews, counts): render it after `renderDefault` so it never pushes
     the rest down, and give the fallback the height of one loaded row.
   - A whole component that loads lazily: a skeleton with the component's height, not `null`.
   - Array items: the list is virtualized and measures each row, so an item fallback that is
     shorter or taller than the loaded row makes the rows below it jump. Match the row height.
5. **Do not suspend on a document that does not exist yet.** A new document only exists once the
   first edit creates it, and SDK hooks that read the current document wait for it forever. Gate
   on `useFormValue(['_createdAt'])`: it is unset until the document exists.
6. **Keep promises stable.** A promise created during render, in `useState` or in `useMemo` is
   thrown away while the component suspends on mount, so `use()` gets a new one every retry and
   never settles. Use the SDK hooks, a module-scope cache keyed by the inputs, or a data library.
7. **Verify.** Open a new document of the type and an existing one: the warning is gone, the rest
   of the form is editable right away, and nothing moves when the async part lands.

## Example

```tsx
import {createDocumentHandle, useDocumentProjection} from '@sanity/sdk-react'
import {Card, Skeleton, Stack, Text} from '@sanity/ui'
import {Suspense} from 'react'
import {type ArrayOfObjectsInputProps, getPublishedId, useFormValue} from 'sanity'

export function ModelSizeInput(props: ArrayOfObjectsInputProps) {
  const documentId = useFormValue(['_id']) as string
  const documentExists = Boolean(useFormValue(['_createdAt']))
  const hasModels = (props.value?.length ?? 0) > 0

  return (
    <Stack gap={3}>
      {props.renderDefault(props)}
      {documentExists && hasModels ? (
        <Suspense fallback={<Skeleton radius={2} style={{height: 33}} animated />}>
          <ModelSizeWarnings documentId={getPublishedId(documentId)} />
        </Suspense>
      ) : null}
    </Stack>
  )
}

function ModelSizeWarnings(props: {documentId: string}) {
  const {data} = useDocumentProjection<{missing: number}>({
    ...createDocumentHandle({documentType: 'product', documentId: props.documentId}),
    projection: `{"missing": count(models[!defined(@->size)])}`,
  })
  return (
    <Card padding={2} radius={2} tone={data.missing > 0 ? 'critical' : 'positive'}>
      <Text size={1}>{data.missing} models are missing a size</Text>
    </Card>
  )
}
```

The skeleton's height matches the one-line card it stands in for. If the loaded UI's height
varies, reserve the most common case and keep the variable part below the input.

© sanity-io · MIT · sanity-io/agent-toolkit

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
nextjs-use-search-params-suspense wsimmonds Скилл nextjs-use-search-params-suspense объясняет, как правильно читать параметры URL в клиентских компонентах Next.js: директива 'use client' плюс обёртка Suspense. CX Codex +1 313установок async-suspense-boundaries tech-leads-club Правило async-suspense-boundaries направляет Claude Code выносить загрузку данных в отдельные компоненты с Suspense, чтобы каркас страницы рендерился без задержек. CX Codex +1 ★ 7 191звёзд репо loading-suspense zebbern Правило loading-suspense требует оборачивать асинхронные компоненты React Three Fiber в Suspense с заглушкой: без границы сцена останется пустой, пока грузится модель или текстура. CX Codex +1 ★ 4 719звёзд репо sanity-live-cache-components sanity-io Скилл sanity-live-cache-components связывает next-sanity с кэшируемыми компонентами Next.js: один общий 'use cache'-барьер, sanityFetch и живая перевалидация через <SanityLive>. CX Codex +1 602установок sanity Mindrally Скилл для работы с Sanity CMS: помогает описывать схемы документов, писать GROQ-запросы и связывать контент с TypeScript. CX Codex +1 767установок dynamic-import patterns.dev Обучает агента разделять бандл через dynamic import(). Скилл помогает отложить загрузку тяжёлых библиотек и диалогов до действий пользователя. CX Codex +1 1 700установок

Из того же набора12

Весь набор →
content-modeling-best-practices Скилл content-modeling-best-practices помогает проектировать типы контента в headless CMS: что вынести в ссылки, что встроить, как не дублировать данные. CX Codex +1 5 200установок content-experimentation-best-practices Скилл content-experimentation-best-practices помогает спланировать контентный A/B-тест, выбрать метрики и разобрать результаты. Пригодится при работе с вариантами в CMS или фронтенде. CX Codex +1 4 100установок portable-text-serialization Скилл portable-text-serialization подсказывает агенту, как рендерить и сериализовать Portable Text в React, Svelte, Vue, Astro, HTML, Markdown и чистый текст. CX Codex +1 3 100установок portable-text-conversion Скилл portable-text-conversion переводит HTML и Markdown в блоки Portable Text для Sanity. Нужен при переносе контента из старой CMS и сборке пайплайнов импорта. CX Codex +1 3 000установок sanity-studio-upgrade Скилл sanity-studio-upgrade читает ваш репозиторий и выдаёт список ломающих изменений, которые касаются именно вашего проекта. Полезен, когда Studio отстал на несколько мажоров. CX Codex +1 827установок sanity-singletons Скилл sanity-singletons для Claude Code настраивает документы-одиночки в Sanity Studio. Он подключается при настройке фиксированных документов или миграции со стороннего плагина. CX Codex +1 392установок Sanity Даёт агенту доступ к контенту, датасетам, релизам и схемам вашего Sanity-проекта. Правки в CMS идут через чат, а не через Studio. CX Codex +1 ★ 201звёзд репо sanity Плагин подключает Claude Code к платформе Sanity, добавляя удалённый MCP-сервер, готовые правила моделирования контента и слэш-команды. ★ 201звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой