Files
simple-react-app-kit/packages/record/docs/en-US/advanced/composition.mdx
T

63 lines
1.9 KiB
Plaintext
Raw Normal View History

2026-09-28 17:24:14 +08:00
---
title: Nested contexts and stable identity
description: Compose local record contexts and select stable React keys for record lists.
order: 20
toc:
- id: nested-records
title: Nested records
- id: optional-provider
title: Optional provider
- id: stable-keys
title: Stable identity
---
## Nested records {#nested-records}
Providers can be nested. Fields inside the inner provider read the local record, and the outer record becomes active again outside that boundary.
```tsx
<RecordProvider value={order}>
<OrderNumber />
<RecordProvider value={order.customer}>
<CustomerName />
</RecordProvider>
</RecordProvider>
```
Do not use record context as a mutable store. Pass a new record reference when new data arrives, and keep editable values in a form or another state layer.
## Optional provider {#optional-provider}
`OptionalRecordProvider` creates a new boundary only when `value` is neither `undefined` nor `null`. A nullish value preserves the nearest parent record, while `0`, `false`, and an empty string still create a new boundary. This is useful for components that accept a prop but can also compose into an existing record view.
```tsx
function ProductCard({ product }: { product?: Product }) {
return (
<OptionalRecordProvider value={product}>
<ProductTitle />
<ProductPrice />
</OptionalRecordProvider>
)
}
```
## Stable identity {#stable-keys}
`RecordsIterator` uses string, number, and bigint records directly as keys. For object records it reads `id` by default. Other values and objects without an `id` can provide a `recordKey` callback; objects can also provide a field name. It falls back to the array index only when no valid key is available.
```tsx
<RecordsIterator
data={locales}
iterator={(locale) => <LocaleRow />}
recordKey="code"
/>
<RecordsIterator
data={revisions}
recordKey={(revision) => `${revision.documentId}:${revision.version}`}
>
<RevisionRow />
</RecordsIterator>
```