Перейти к основному содержимому

useFormControlValue()

function useFormControlValue<T>(control): T;

Defined in: platforms/react/hooks/useFormControlValue.ts:176

React-хук для подписки только на значение поля.

Оптимизированная версия useFormControl, которая подписывается только на сигнал value. Компонент не будет ре-рендериться при изменении issues, touched, valid и других свойств состояния.

Когда использовать​

  • Условный рендеринг на основе значения другого поля
  • Вычисляемые значения зависящие от значения поля
  • Read-only отображение значения без интерактивности
  • Оптимизация производительности когда не нужны другие свойства состояния

Когда НЕ использовать​

Если компоненту нужны issues, touched, disabled или другие свойства - используйте useFormControl. Множественные подписки на один контрол через разные хуки менее эффективны, чем одна подписка через useFormControl.

Type Parameters​

T​

T

Тип значения поля

Parameters​

control​

FormControl<T>

FormControl для подписки на значение

Returns​

T

Текущее значение поля

Examples​

import { useFormControlValue } from '@reformer/core/react';

interface FormFields {
hasShipping: FormControl<boolean>;
shippingAddress: FormGroup<AddressFields>;
}

function ShippingSection({ form }: { form: FormFields }) {
// Подписка только на значение checkbox
const hasShipping = useFormControlValue(form.hasShipping);

if (!hasShipping) {
return null;
}

return (
<div className="shipping-section">
<h3>Shipping Address</h3>
<AddressForm control={form.shippingAddress} />
</div>
);
}
interface FormFields {
country: FormControl<string>;
city: FormControl<string>;
}

function CitySelect({ form }: { form: FormFields }) {
const country = useFormControlValue(form.country);
const { value, disabled } = useFormControl(form.city);

// Получаем города для выбранной страны
const cities = useMemo(() => getCitiesForCountry(country), [country]);

// Сбрасываем город при смене страны
useEffect(() => {
form.city.setValue('');
}, [country, form.city]);

return (
<select
value={value}
disabled={disabled || !country}
onChange={e => form.city.setValue(e.target.value)}
>
<option value="">Select city...</option>
{cities.map(city => (
<option key={city.id} value={city.id}>{city.name}</option>
))}
</select>
);
}
interface OrderItem {
quantity: number;
price: number;
}

// Хук вызывается на уровне компонента-строки (не в цикле — Rules of Hooks).
// Доступ к полям элемента — через Proxy: item.quantity, item.price.
function OrderRow({ item }: { item: FormGroup<OrderItem> }) {
const quantity = useFormControlValue(item.quantity);
const price = useFormControlValue(item.price);

return <span>Итого: ${(quantity * price).toFixed(2)}</span>;
}

function OrderList({ items }: { items: FormArray<OrderItem> }) {
return (
<div>
{items.map((item, index) => (
<OrderRow key={index} item={item} />
))}
</div>
);
}
interface MarkdownEditorProps {
control: FormControl<string>;
}

function MarkdownPreview({ control }: MarkdownEditorProps) {
// Подписка только на значение для preview
const markdown = useFormControlValue(control);

const html = useMemo(() => marked(markdown), [markdown]);

return (
<div
className="markdown-preview"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}

// Основной редактор использует useFormControl для полного состояния
function MarkdownEditor({ control }: MarkdownEditorProps) {
const { value, shouldShowIssues, issues } = useFormControl(control);
const message = useIssueMessage(); // из '@reformer/core/react'

return (
<div className="editor-container">
<textarea
value={value}
onChange={e => control.setValue(e.target.value)}
/>
{shouldShowIssues && <span className="error">{message(issues[0])}</span>}

{/* Preview обновляется только при изменении value *}
<MarkdownPreview control={control} />
</div>
);
}
function CharacterCounter({ control, max }: { control: FormControl<string>; max: number }) {
const value = useFormControlValue(control);
const remaining = max - value.length;

return (
<span className={remaining < 20 ? 'warning' : ''}>
{remaining} characters remaining
</span>
);
}

See​