useNativeFieldSync
Re-renders a component whenever a native form element's value changes, including form library writes and form resets, without copying the value into state.
Overview
useNativeFieldSync keeps UI that is derived from a native form element in step with it, while the element stays the source of truth. The host re-renders on every input and change event the element emits, whether from your own code or from a form library writing to it (React Hook Form, Formik). A native form.reset() emits neither, so the hook also listens for the form's reset event and re-emits input and change once the reset has applied.
Select uses it to keep its trigger label in sync with the hidden native field, and VerificationCode (through useVerificationCode) uses it for its cells. Use it directly when you build a custom field around a hidden or native input and need the visible part to follow the input's value.
Import
import { useNativeFieldSync } from '@unflowio/ui/hooks/useNativeFieldSync';Parameters
| Param | Type | Description |
|---|---|---|
ref | RefObject<E | null> | Required. The native element. E is any element with a form property: HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement |
readValue | (node: E) => string | Required. Reads the value that should trigger a re-render, e.g. (node) => node.value |
Return value
None. After a change the host re-renders, so read the element directly during render (ref.current?.value).
Usage
import { useRef } from 'react';
import { useNativeFieldSync } from '@unflowio/ui/hooks/useNativeFieldSync';
const plans = [
{ value: 'business', label: 'Business' },
{ value: 'enterprise', label: 'Enterprise' },
];
export function PlanField({ name, defaultValue }: { name: string; defaultValue?: string }) {
const selectRef = useRef<HTMLSelectElement>(null);
useNativeFieldSync(selectRef, (node) => node.value);
const current = plans.find((plan) => plan.value === selectRef.current?.value);
return (
<label>
Plan
<select ref={selectRef} name={name} defaultValue={defaultValue}>
{plans.map((plan) => (
<option key={plan.value} value={plan.value}>
{plan.label}
</option>
))}
</select>
<span>Selected: {current?.label ?? 'None'}</span>
</label>
);
}form.reset(), a React Hook Form setValue or a change from the user all update the "Selected" text, without the value ever living in React state.
Implementation notes
- It is built on
useSyncExternalStore.readValueonly needs to return something that changes when the element's value does; the result isn't returned to you. - Listeners are attached when the component subscribes. If
ref.currentisnullat that point (e.g. the element renders conditionally after mount), nothing is attached. - During server rendering the snapshot is an empty string.
- Programmatic writes to
node.valuedon't emit events. Dispatch aninputorchangeevent after setting the value, which is also what form libraries expect.