@base-ui/react
Version:
Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.
36 lines (34 loc) • 1.3 kB
JavaScript
'use client';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { useRefWithInit } from '@base-ui/utils/useRefWithInit';
import { useFieldRootContext } from "../field-root-context/FieldRootContext.mjs";
export function useRegisterFieldControl(controlRef, id, value, getFormValueOverride, enabled = true, name) {
const {
registerFieldControl
} = useFieldRootContext();
const sourceRef = useRefWithInit(() => Symbol());
// Re-register without unregistering first: re-registration with the same id updates the
// form's fields Map entry in place, while a delete + re-add would move the field to the
// end of the Map every time its value changes.
useIsoLayoutEffect(() => {
const source = sourceRef.current;
if (!enabled) {
registerFieldControl(source, undefined);
return;
}
const registration = {
controlRef,
getValue: getFormValueOverride,
id,
name,
value
};
registerFieldControl(source, registration);
}, [controlRef, enabled, getFormValueOverride, id, name, registerFieldControl, sourceRef, value]);
useIsoLayoutEffect(() => {
const source = sourceRef.current;
return () => {
registerFieldControl(source, undefined);
};
}, [registerFieldControl, sourceRef]);
}