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

react-selective-hydration — скилл для Claude Code: обзор и установка

Скилл учит агента настраивать выборочную гидратацию и потоковый SSR в React 18+. Пригодится, когда тяжёлые компоненты с запросами данных тормозят интерактивность страницы.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PatternsDev/skills --skill react-selective-hydration -a claude-code
Открыть на GitHub

Что делает react-selective-hydration

В классическом SSR вызов renderToString блокирует отправку HTML, пока сервер не соберёт всё дерево целиком. Клиенту при этом приходится скачивать весь JS-бандл до старта гидратации. Этот скилл инструктирует модель использовать архитектуру React 18: связку hydrateRoot, границы Suspense и потоковый рендеринг.

Внутри зафиксированы правила для серверной части: renderToPipeableStream для среды Node и renderToReadableStream для Web Streams или edge. Скилл учит изолировать медленные компоненты вроде списков комментариев в Suspense. В итоге браузер сразу отображает fallback-заглушки и гидрирует критичные интерактивные блоки ещё до загрузки тяжёлых скриптов.

Для работы архитектуры проект обязан использовать React 18+ с методом hydrateRoot. Если поместить критически важные для пользователя интерактивные элементы внутрь долгих fallback-заглушек Suspense, польза от выборочной гидратации пропадёт.

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

  • настроить потоковый SSR через renderToPipeableStream или renderToReadableStream
  • разделить дерево компонентов на независимые части с помощью Suspense
  • подключить hydrateRoot для поэтапной гидратации интерфейса
  • предотвратить блокировку интерактивности страницы тяжёлыми запросами данных

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

  • Переведи SSR в этом проекте с renderToString на renderToPipeableStream с выборочной гидратацией
  • Оберни блок с комментариями в Suspense, чтобы его загрузка не блокировала гидратацию остальной страницы
  • Проверь файл entry.server.tsx и настрой потоковый рендеринг для среды Node

Как установить react-selective-hydration

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill react-selective-hydration -a claude-code

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

~/.claude/skills/react-selective-hydration/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/react-selective-hydration/

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

Вопросы о react-selective-hydration

Как установить react-selective-hydration в Claude Code?

Выполните команду npx skills add PatternsDev/skills --skill react-selective-hydration -a claude-code в терминале проекта.

Что делает скилл react-selective-hydration?

Он передаёт ИИ-ассистенту правила проектирования потокового SSR и выборочной гидратации в React 18+. Модель учится расставлять границы Suspense и использовать потоковые методы рендеринга.

Какие серверные методы предлагает внедрять этот скилл?

Скилл рекомендует renderToPipeableStream для среды Node и renderToReadableStream для edge-окружения на Web Streams.

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

SKILL.md · MIT
---
name: react-selective-hydration
description: Teaches selective hydration combined with streaming SSR in React 18+. Use when you need to prioritize hydrating interactive components while streaming the rest of the page.
paths:
  - "**/*.tsx"
  - "**/*.jsx"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "hooks-pattern"
  - "hoc-pattern"
---

# Selective Hydration

In previous articles, we covered how SSR with hydration can improve user experience. React is able to (quickly) generate a tree on the server using the `renderToString` method that the `react-dom/server` library provides, which gets sent to the client after the entire tree has been generated. The rendered HTML is non interactive, until the JavaScript bundle has been fetched and loaded, after which React walks down the tree to hydrate and attaches the handlers.

However, this approach can lead to some performance issues due to some limitations with the current implementation.

## When to Use

- Use this when you want to make parts of your SSR page interactive before all JavaScript has loaded
- This is helpful when slow components (e.g., data-fetching components) are blocking the entire page's hydration

## Instructions

- Use `Suspense` boundaries to delineate independently hydratable chunks of UI
- Use `renderToPipeableStream` (Node) or `renderToReadableStream` (edge) for streaming SSR
- Place heavy data-fetching components inside `Suspense` so they don't delay sibling hydration
- Ensure critical interactive components are not inside long-lived loading fallbacks
- Use `hydrateRoot` (React 18+) to benefit from selective hydration

## Details

Before the server-rendered HTML tree is able to get sent to the client, all components need to be ready. This means that components that may rely on an external API call or any process that could cause some delays, might end up blocking smaller components from being rendered quickly.

Besides a slower tree generation, another issue is the fact that React only hydrates the tree once. This means that before React is able to hydrate any of the components, it needs to have fetched the JavaScript for all of the components before it's able to hydrate any of them. This means that smaller components (with smaller bundles) have to wait for the larger components's code to be fetched and loaded, until React is able to hydrate anything on your website. During this time, the website remained non-interactive.

React 18 solves these problems by allowing us to combine streaming server-side rendering with a new approach to hydration: Selective Hydration!

Instead of using `renderToString`, modern React SSR uses `renderToPipeableStream()` on Node runtimes or `renderToReadableStream()` on Web Stream runtimes.

These APIs, in combination with `hydrateRoot()` and `Suspense`, make it possible to start streaming HTML without having to wait for the larger components to be ready. This means that we can lazy-load components when using SSR without blocking the hydration of the rest of the page.

The `Comments` component, which earlier slowed down the tree generation and TTI, is now wrapped in `Suspense`. This tells React to not let this component slow down the rest of the tree generation. Instead, React inserts the fallback components as the initially rendered HTML, and continues to generate the rest of the tree before it's sent to the client.

In the meantime, we're still fetching the external data that we need for the `Comments` component.

Selective hydration makes it possible to already hydrate the components that were sent to the client, even before the `Comments` component has been sent!

Once the data for the `Comments` component is ready, React starts streaming the HTML for this component, as well as a small `<script>` to replace the fallback loader.

React starts the hydration after the new HTML has been injected.

React 18 fixes some issues that people often encountered when using SSR with React.

Streaming rendering allows you to start streaming components as soon as they're ready, without risking a slower FCP and TTI due to components that might take longer to generate on the server.

Components can be hydrated as soon as they're streamed to the client, since we no longer have to wait for all JavaScript to load to start hydrating and can start interacting with the app before all components have been hydrated.

## Source

- [patterns.dev/react/react-selective-hydration](https://patterns.dev/react/react-selective-hydration)

### References

- [New Suspense SSR Architecture in React 18](https://github.com/reactwg/react-18/discussions/37)

© patterns.dev · MIT · PatternsDev/skills

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

Всё по теме «Фронтенд и UI» →
react-modernization Seth Hobson Скилл обновляет React-код, переносит классовые компоненты на хуки и помогает внедрять возможности React 18. Подойдёт для поэтапной модернизации старого приложения. CX Codex 12 625установок react-best-practices vercel Скилл для разбора медленного интерфейса на React и Next.js: находит водопады запросов, лишний JS в бандле, ошибки на границе сервер-клиент и пустые ререндеры. CX Codex +1 399установок nuxt4-patterns affaan-m Скилл для работы с Nuxt 4: гидратация, route rules, ленивая загрузка и SSR-безопасный сбор данных через useFetch и useAsyncData. CX Codex +1 4 600установок angular-ssr analogjs Скилл для задач Angular SSR, гидратации и пререндеринга. Он устарел: текущая версия больше не поддерживается. CX Codex +1 3 900установок astro-framework delineas Скилл для ИИ-агента, который разбирается в islands architecture, гидратации и Content Layer API. Пригодится, когда проект на Astro растёт и нужно решить, что рендерить на сервере, а что в браузере. CX Codex +1 2 200установок framer-motion-react C-Jeril Скилл по Framer Motion для React и Next.js: AnimatePresence, layout-анимации, useAnimation и обход проблем с SSR. CX Codex +1 822установок

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

hoc-pattern Обучает ИИ паттерну Higher-Order Component для переиспользования логики в React. Пригодится при выносе авторизации, логов или загрузки данных. CX Codex +1 1 000установок compound-pattern Учит агента собирать составные компоненты с общим неявным состоянием: табы, аккордеоны, выпадающие меню. Пригодится, когда подкомпоненты должны согласовывать поведение без прокидывания пропсов. CX Codex +1 1 000установок react-server-components Скилл объясняет React Server Components: какие компоненты рендерить на сервере и где ставить 'use client'. Пригодится в Next.js App Router. CX Codex +1 954установок progressive-hydration Скилл объясняет агенту, как разбить гидратацию серверного React-приложения на части и отложить JavaScript для неважных блоков. CX Codex +1 952установок server-side-rendering Скилл объясняет серверный рендеринг в React и подсказывает, когда он оправдан, а когда хватит статики или клиентского рендеринга. CX Codex +1 942установок incremental-static-rendering Скилл учит агента настраивать Incremental Static Regeneration в Next.js. Он помогает обновлять статичные страницы без полной пересборки сайта. CX Codex +1 918установок static-rendering Скилл объясняет статическую генерацию: какие страницы можно собрать в HTML заранее и как это сделать в Next.js. Пригодится, когда контент не меняется от запроса к запросу. CX Codex +1 910установок streaming-ssr Учит агента отдавать HTML чанками через renderToPipeableStream и Suspense. Пригодится, когда страница большая и ждать полной отрисовки перед первым байтом нельзя. CX Codex +1 883установок

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

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