Библиотека промптов

Промпты: React

Промпты для компонентов React: поиск лишних перерисовок, разделение крупных компонентов и написание тестов, следующих поведению пользователя.

Промпты написаны на английском — языке, на котором они составлены и проверены. Описания и инструкции на этих страницах переведены.

  • performance
  • hooks
  • components
100/100 · 153 токенов

Аудит перерисовок React

Находит причины лишних перерисовок в компоненте и предлагает для каждой минимальное исправление.

Используйте, когда: Компонент работает медленно или профайлер показывает, что он перерисовывается при каждом нажатии клавиши.

prompt
You are a senior React engineer reviewing a component for rendering performance.

## Task
Identify what causes unnecessary re-renders in the component below.

## Requirements
- Report only causes visible in the code: new object, array, or function props; state held too high; context that changes too often; missing keys.
- Quote the line for every cause.
- Give the smallest change that removes each cause.
- Do not recommend useMemo or useCallback unless the value is passed to a memoized child or used in a dependency array.

## Output format
Return a numbered list. Each item has three labeled lines: Cause, Line, and Fix. End with one sentence naming the fix to apply first.

## Input
<component>
{{component}}
</component>

Переменные

{{component}}
Исходный код компонента, при наличии — с отрисовываемыми дочерними компонентами.

Пример ввода

component: a SearchPage that passes `filters={{ status, tag }}` to a memoized ResultsList.

Пример вывода

1. Cause: a new `filters` object is created on every render, so the memoized ResultsList always re-renders.
   Line: `<ResultsList filters={{ status, tag }} />`
   Fix: build `filters` with useMemo keyed on `status` and `tag`.

Apply fix 1 first.

Иллюстрация: написан, чтобы показать ожидаемую форму, а не создан моделью.

  • testing
  • react testing library
  • components
100/100 · 158 токенов

Тесты на React Testing Library

Пишет тесты, работающие с компонентом так, как это делает пользователь, с запросами по роли и подписи.

Используйте, когда: У компонента нет тестов или тесты ломаются при каждом рефакторинге, потому что проверяют детали реализации.

prompt
You are a senior React engineer writing tests with React Testing Library and Vitest.

## Task
Write tests for the component below that cover the behaviors listed.

## Requirements
- Query elements by role, label, or text; never by class name or test id.
- Use userEvent for every interaction.
- Write one test per behavior, named as a sentence describing what the user sees.
- Mock only the network calls named in the behaviors.
- Do not test internal state or the number of renders.

## Output format
Return one TypeScript code block containing the complete test file, followed by a bulleted list of any listed behavior you could not test and why.

## Input
<component>
{{component}}
</component>

<behaviors>
{{behaviors}}
</behaviors>

Переменные

{{component}}
Исходный код компонента.
{{behaviors}}
Покрываемые виды поведения, по одному в строке.

Пример ввода

component: a LoginForm with email and password fields.
behaviors: shows an error when the email is empty; disables the button while submitting.

Пример вывода

```tsx
it('shows an error when the email is empty', async () => {
  render(<LoginForm />);
  await userEvent.click(screen.getByRole('button', { name: /sign in/i }));
  expect(screen.getByRole('alert')).toHaveTextContent(/email is required/i);
});
```

Иллюстрация: написан, чтобы показать ожидаемую форму, а не создан моделью.

Сделайте его своим

Измените требования под свои стандарты, затем проверьте результат. Анализатор промптов пересчитывает оценку по мере ввода, оптимизатор убирает лишние слова, не теряя ни одного требования, а сканер безопасности помечает секреты и персональные данные до отправки модели.

Другие категории