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

incremental-static-rendering — скилл для Claude Code: установка

Скилл учит агента настраивать Incremental Static Regeneration в Next.js. Он помогает обновлять статичные страницы без полной пересборки сайта.

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

Что делает incremental-static-rendering

Скилл добавляет правила и примеры реализации Incremental Static Regeneration для файлов **/*.tsx и **/*.jsx. Ассистент узнаёт, как отдавать страницы по схеме stale-while-revalidate, настраивать revalidate внутри getStaticProps и применять fallback: true в getStaticPaths для ленивой генерации новых путей при первом запросе.

Для Next.js 13+ и App Router скилл предписывает использовать generateStaticParams и асинхронные компоненты вместе со сбросом кэша через revalidatePath или revalidateTag. Если фоновое обновление завершается ошибкой на сервере, Next.js продолжает отдавать старую версию без сбоев для посетителей.

Для биржевых котировок и персональных профилей этот подход сломает интерфейс: рассинхрон версий у разных читателей создаст путаницу, поэтому для них нужен SSR. Механизм рассчитан на каталоги товаров и блоги в проектах на Next.js 9.5 и новее.

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

  • настроить фоновое обновление страниц через revalidate
  • добавить ленивую генерацию новых маршрутов с fallback: true
  • настроить сброс кэша по событию через revalidatePath
  • перевести статические страницы на ISR в Next.js App Router

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

  • Настрой фоновую регенерацию для каталога товаров в getStaticProps с интервалом 60 секунд
  • Сделай ленивую генерацию страниц блога через getStaticPaths с fallback: true
  • Покажи, как перевести этот компонент на ISR в Next.js App Router через generateStaticParams

Как установить incremental-static-rendering

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill incremental-static-rendering -a claude-code

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

~/.claude/skills/incremental-static-rendering/SKILL.md

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

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

Вопросы о incremental-static-rendering

Как установить incremental-static-rendering в Claude Code?

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

Что делает скилл incremental-static-rendering?

Он обучает ассистента паттерну инкрементальной статической регенерации в Next.js. Скилл объясняет, как настроить stale-while-revalidate, ленивое добавление страниц и сброс кэша без полной пересборки проекта.

С какими версиями Next.js работает этот паттерн?

Базовый механизм revalidate поддерживается начиная с Next.js 9.5 в Pages Router. Для проектов на Next.js 13 и новее скилл содержит инструкции по настройке через App Router и generateStaticParams.

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

SKILL.md · MIT
---
name: incremental-static-rendering
description: Teaches Incremental Static Regeneration (ISR) for updating static content post-build. Use when you have static pages that need periodic updates without a full site rebuild.
paths:
  - "**/*.tsx"
  - "**/*.jsx"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "hooks-pattern"
  - "hoc-pattern"
---

# Incremental Static Generation

Static Generation (SSG) addresses most of the concerns of SSR and CSR but is suitable for rendering mostly static content. It poses limitations when the content to be rendered is dynamic or changing frequently.

Think of a growing blog with multiple posts. You wouldn't possibly want to rebuild and redeploy the site just because you want to correct a typo in one of the posts. Similarly, one new blog post should also not require a rebuild for all the existing pages. Thus, SSG on its own is not enough for rendering large websites or applications.

## When to Use

- Use this when you have mostly static pages that need periodic data updates without full rebuilds
- This is helpful for large sites (blogs, e-commerce) where rebuilding every page on each change is impractical

## When NOT to Use

- When content changes in real-time and stale data is unacceptable (e.g., live scores, stock tickers)
- For pages that are fully dynamic and personalized per user — SSR is a better fit
- When the revalidation window creates a confusing experience where different users see different content versions

## Instructions

- Use `revalidate` in `getStaticProps` to set a time interval for background page regeneration
- Use `fallback: true` in `getStaticPaths` to lazily generate pages on first request
- Consider on-demand revalidation (`revalidatePath`, `revalidateTag`) for immediate updates after content changes
- In Next.js 13+ App Router, use `generateStaticParams` and async components for ISR

## Details

The Incremental Static Generation (iSSG) pattern was introduced as an upgrade to SSG, to help solve the dynamic data problem and help static sites scale for large amounts of frequently changing data. iSSG allows you to update existing pages and add new ones by pre-rendering a subset of pages in the background even while fresh requests for pages are coming in.

### Sample Code

iSSG works on two fronts to incrementally introduce updates to an existing static site after it has been built.

1. Allows addition of new pages
2. Allows updates to existing pages also known as Incremental Static "Re"generation

#### Adding New pages

The lazy loading concept is used to include new pages on the website after the build. This means that the new page is generated immediately on the first request. While the generation takes place, a fallback page or a loading indicator can be shown to the user on the front-end.

```js
export async function getStaticPaths() {
  const products = await getProductsFromDatabase();

  const paths = products.map((product) => ({
     params: { id: product.id }
  }));

  // fallback: true means that the missing pages
  // will not 404, and instead can render a fallback.
  return { paths, fallback: true };
}

// params will contain the id for each generated page.
export async function getStaticProps({ params }) {
  return {
    props: {
      product: await getProductFromDatabase(params.id)
    }
  }
}

export default function Product({ product }) {
  const router = useRouter();

  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  // Render product
}
```

Here, we have used `fallback: true`. Now if the page corresponding to a specific product is unavailable, we show a fallback version of the page, eg., a loading indicator as shown in the Product function above. Meanwhile, Next.js will generate the page in the background. Once it is generated, it will be cached and shown instead of the fallback page. The cached version of the page will now be shown to any subsequent visitors immediately upon request.

#### Update Existing pages

To re-render an existing page, a suitable timeout is defined for the page. This will ensure that the page is revalidated whenever the defined timeout period has elapsed. The user will continue to see the previous version of the page, till the page has finished revalidation. Thus, iSSG uses the [stale-while-revalidate](https://web.dev/stale-while-revalidate/) strategy where the user receives the cached or stale version while the revalidation takes place. The revalidation takes place completely in the background without the need for a full rebuild.

```js
// This function runs at build time on the build server
export async function getStaticProps() {
  return {
    props: {
      products: await getProductsFromDatabase(),
      revalidate: 60, // This will force the page to revalidate after 60 seconds
    }
  }
}

// The page component receives products prop from getStaticProps at build time
export default function Products({ products }) {
  return (
    <>
      <h1>Products</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </>
  )
}
```

The code to revalidate the page after 60 seconds is included in the `getStaticProps()` function. When a request comes in the available static page is served first. Every one minute the static page gets refreshed in the background with new data. Once generated, the new version of the static file becomes available and will be served for any new requests in the subsequent minute. This feature is available in Next.js 9.5 and above.

### Advantages

iSSG provides all the advantages of SSG and then some more:

1. **Dynamic data**: Its ability to support dynamic data without a need to rebuild the site.
2. **Speed**: iSSG is at least as fast as SSG because data retrieval and rendering still takes place in the background. There is little processing required on the client or the server.
3. **Availability**: A fairly recent version of any page will always be available online for users to access. Even if the regeneration fails in the background, the old version remains unaltered.
4. **Consistent**: As the regeneration takes place on the server one page at a time, the load on the database and the backend is low and performance is consistent. As a result, there are no spikes in latency.
5. **Ease of Distribution**: Just like SSG sites, iSSG sites can also be distributed through a network of CDN's used to serve pre-rendered web pages.

## Source

- [patterns.dev/react/incremental-static-rendering](https://patterns.dev/react/incremental-static-rendering)

© patterns.dev · MIT · PatternsDev/skills

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

Всё по теме «Фронтенд и UI» →
astro astrolicious Скилл для работы с фреймворком Astro: страницы, компоненты, адаптеры SSR, коллекции контента и деплой. Пригодится, когда проект уже на Astro или вы только начинаете его. CX Codex +1 18 200установок sveltekit Claude MPM Team Скилл подсказывает агенту, как устроен SvelteKit: файловый роутинг, load-функции, form actions и адаптеры для деплоя. CX Codex +1 441установок vercel-react-view-transitions vercel Скилл ведёт агента по нативным view transitions в React: переходы между страницами, общие элементы, появление и исчезновение блоков без сторонних библиотек. CX Codex +1 168 100установок gsap-react greensock Скилл подсказывает, как создавать анимации GSAP в React и Next.js, ограничивать их область действия и очищать при размонтировании компонента. CX Codex +1 66 300установок clerk-custom-ui clerk Скилл по Clerk: агент собирает свою форму входа на хуках useSignIn и useSignUp либо перекрашивает готовые компоненты под бренд. CX Codex +1 55 200установок clerk-nextjs-patterns clerk Скилл обучает ИИ-агента паттернам аутентификации Clerk в Next.js: от серверных функций до кэширования. Пригодится при настройке middleware, Server Actions и защите роутов. CX Codex +1 53 400установок

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

react-server-components Скилл объясняет React Server Components: какие компоненты рендерить на сервере и где ставить 'use client'. Пригодится в Next.js App Router. CX Codex +1 954установок progressive-hydration Скилл объясняет агенту, как разбить гидратацию серверного React-приложения на части и отложить JavaScript для неважных блоков. CX Codex +1 952установок react-selective-hydration Скилл учит агента настраивать выборочную гидратацию и потоковый SSR в React 18+. Пригодится, когда тяжёлые компоненты с запросами данных тормозят интерактивность страницы. CX Codex +1 943установок server-side-rendering Скилл объясняет серверный рендеринг в React и подсказывает, когда он оправдан, а когда хватит статики или клиентского рендеринга. CX Codex +1 942установок static-rendering Скилл объясняет статическую генерацию: какие страницы можно собрать в HTML заранее и как это сделать в Next.js. Пригодится, когда контент не меняется от запроса к запросу. CX Codex +1 910установок streaming-ssr Учит агента отдавать HTML чанками через renderToPipeableStream и Suspense. Пригодится, когда страница большая и ждать полной отрисовки перед первым байтом нельзя. CX Codex +1 883установок js-performance-patterns Набор паттернов микрооптимизации JavaScript для горячих путей. Помогает агенту устранять просадки скорости в циклах, обработчиках событий и операциях с DOM. CX Codex +1 687установок view-transitions Учит агента работать с View Transitions API: переходы между страницами и состояниями интерфейса браузер анимирует сам. CX Codex +1 678установок

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

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