list-performance-function-references — правило для Claude Code
Правило list-performance-function-references запрещает трансформировать массивы перед передачей в виртуализированные списки. Оно заставляет переносить вычисления внутрь элементов, сохраняя стабильные ссылки на данные.
MIT ★ 1 216 обновлён 2026-10-24
/plugin marketplace add fcakyon/claude-codex-settings
/plugin install react-skills@claude-settingsЧто делает list-performance-function-references
Правило инструктирует модель не использовать .map() или фильтрацию прямо перед передачей массива в виртуализированный список вроде LegendList или FlatList. Виртуализация опирается на стабильность ссылок на объекты: создание новых объектов на каждый рендер родителя заставляет список заново перерисовывать все видимые элементы.
Вместо прокидывания динамических свойств через родительский компонент правило требует сдвигать трансформации внутрь дочерних элементов списка. Для динамических данных предлагается использовать селекторы Zustand или селекторы контекста прямо в renderItem. Сортировка массива через toSorted() допускается, поскольку ссылки на внутренние объекты при этом сохраняются.
Если проект собирается без React Compiler, обёртка renderItem в useCallback остаётся обязательной, иначе родительский рендер продолжит сбрасывать мемоизацию.
Какие задачи решает
- устранить лишние ререндеры виртуализированных списков при вводе текста
- сохранить стабильные ссылки на объекты данных для FlatList и LegendList
- перенести вычисление производного состояния внутрь элементов списка
- настроить селекторы Zustand для точечного обновления компонентов
Примеры запросов агенту
- Оптимизируй рендеринг списка товаров, чтобы он не тормозил при фильтрации
- Проверь компонент поиска с виртуализированным списком по правилу list-performance-function-references
- Вынеси вычисление статуса избранного из родителя внутрь элемента списка
Как установить list-performance-function-references
1Через маркетплейс плагинов
/plugin marketplace add fcakyon/claude-codex-settings/plugin install react-skills@claude-settings2Вручную: положить файлы
.claude/rules/list-performance-function-references.mdПоле paths во frontmatter ограничивает файлы
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.cursor/rules/list-performance-function-references.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.github/instructions/list-performance-function-references.instructions.mdПоле applyTo задаёт, к каким файлам применять
Вручную: положить файлы
.devin/rules/list-performance-function-references.mdВручную: положить файлы
.clinerules/list-performance-function-references.mdПо шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать
Вопросы о list-performance-function-references
Как установить list-performance-function-references в Claude Code?
Подключите маркетплейс командой /plugin marketplace add fcakyon/claude-codex-settings, затем выполните /plugin install react-skills@claude-settings. Также можно сохранить файл правила по пути .claude/rules/list-performance-function-references.md.
Что делает правило list-performance-function-references?
Оно запрещает генерировать новые ссылки на объекты перед передачей в виртуализированные списки и требует получать динамические значения через селекторы внутри самих элементов.
Можно ли сортировать массив данных в родительском компоненте?
Да, создание нового массива через метод вроде toSorted() допустимо, если ссылки на сами объекты внутри массива остаются неизменными.
Исходный текст
list-performance-function-references.md · MIT
---
title: Optimize List Performance with Stable Object References
impact: CRITICAL
impactDescription: virtualization relies on reference stability
tags: lists, performance, flatlist, virtualization
---
## Optimize List Performance with Stable Object References
Don't map or filter data before passing to virtualized lists. Virtualization
relies on object reference stability to know what changed—new references cause
full re-renders of all visible items. Attempt to prevent frequent renders at the
list-parent level.
Where needed, use context selectors within list items.
**Incorrect (creates new object references on every keystroke):**
```tsx
function DomainSearch() {
const { keyword, setKeyword } = useKeywordZustandState()
const { data: tlds } = useTlds()
// Bad: creates new objects on every render, reparenting the entire list on every keystroke
const domains = tlds.map((tld) => ({
domain: `${keyword}.${tld.name}`,
tld: tld.name,
price: tld.price,
}))
return (
<>
<TextInput value={keyword} onChangeText={setKeyword} />
<LegendList
data={domains}
renderItem={({ item }) => <DomainItem item={item} keyword={keyword} />}
/>
</>
)
}
```
**Correct (stable references, transform inside items):**
```tsx
const renderItem = ({ item }) => <DomainItem tld={item} />
function DomainSearch() {
const { data: tlds } = useTlds()
return (
<LegendList
// good: as long as the data is stable, LegendList will not re-render the entire list
data={tlds}
renderItem={renderItem}
/>
)
}
function DomainItem({ tld }: { tld: Tld }) {
// good: transform within items, and don't pass the dynamic data as a prop
// good: use a selector function from zustand to receive a stable string back
const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.name)
return <Text>{domain}</Text>
}
```
**Updating parent array reference:**
Creating a new array instance can be okay, as long as its inner object
references are stable. For instance, if you sort a list of objects:
```tsx
// good: creates a new array instance without mutating the inner objects
// good: parent array reference is unaffected by typing and updating "keyword"
const sortedTlds = tlds.toSorted((a, b) => a.name.localeCompare(b.name))
return <LegendList data={sortedTlds} renderItem={renderItem} />
```
Even though this creates a new array instance `sortedTlds`, the inner object
references are stable.
**With zustand for dynamic data (avoids parent re-renders):**
```tsx
const useSearchStore = create<{ keyword: string }>(() => ({ keyword: '' }))
function DomainSearch() {
const { data: tlds } = useTlds()
return (
<>
<SearchInput />
<LegendList
data={tlds}
// if you aren't using React Compiler, wrap renderItem with useCallback
renderItem={({ item }) => <DomainItem tld={item} />}
/>
</>
)
}
function DomainItem({ tld }: { tld: Tld }) {
// Select only what you need—component only re-renders when keyword changes
const keyword = useSearchStore((s) => s.keyword)
const domain = `${keyword}.${tld.name}`
return <Text>{domain}</Text>
}
```
Virtualization can now skip items that haven't changed when typing. Only visible
items (~20) re-render on keystroke, rather than the parent.
**Deriving state within list items based on parent data (avoids parent
re-renders):**
For components where the data is conditional based on the parent state, this
pattern is even more important. For example, if you are checking if an item is
favorited, toggling favorites only re-renders one component if the item itself
is in charge of accessing the state rather than the parent:
```tsx
function DomainItemFavoriteButton({ tld }: { tld: Tld }) {
const isFavorited = useFavoritesStore((s) => s.favorites.has(tld.id))
return <TldFavoriteButton isFavorited={isFavorited} />
}
```
Note: if you're using the React Compiler, you can read React Context values
directly within list items. Although this is slightly slower than using a
Zustand selector in most cases, the effect may be negligible.
© fcakyon · MIT · fcakyon/claude-codex-settings