watching varying fields (by registered name) causes app to slow down
i have a very complicated advanced edit form. i want to not show some fields depending on other's value. for that im using the watch api from react-hook-form. the problem is that since my form is nested im registering some fields by their index in the array. if there will be 5 of them my utility function registers them like this
a.b.0.visa_req
a.b.1.visa_req
a.b.2.visa_req
a.b.3.visa_req
a.b.4.visa_req
there fore, im watching them like this in this code.
//this watches only the 0th index. i want to watch them all
const watchingValidity = watch("a.b.0.min_validity_req");
let updatedHiddenFields = [...hiddenFields];
React.useEffect(() => {
if (watching.a && watching.a.b) {
watching.a.b.forEach((item, index) => {
const field =
if (item.visa_req === "not_required" && !updatedHiddenFields.includes(field)) {
updatedHiddenFields.push(field);
setHiddenFields(updatedHiddenFields);
} else if (item.visa_req === "required") {
updatedHiddenFields = updatedHiddenFields.filter(f => f !== field);
setHiddenFields(updatedHiddenFields);
}
});
}
}, [watching]);
React.useEffect(() => {
const fieldKeys = [
];
setHiddenFields(watchingValidity ? updatedHiddenFields.filter(f => !fieldKeys.includes(f)) : [...updatedHiddenFields, ...fieldKeys]);
}, [watchingValidity]);
when one value changes i dont want to update the whole form. i want to update just one field. thats why its working so slowly.
any solution ideas??
watchin a.b has also the same effect as watching a.b.${index}.visa_req
a.b.0.visa_req
a.b.1.visa_req
a.b.2.visa_req
a.b.3.visa_req
a.b.4.visa_req
there fore, im watching them like this in this code.
//this watches only the 0th index. i want to watch them all
const watchingValidity = watch("a.b.0.min_validity_req");
let updatedHiddenFields = [...hiddenFields];
React.useEffect(() => {
if (watching.a && watching.a.b) {
watching.a.b.forEach((item, index) => {
const field =
a.b.${index}.visa_info_group; // the field that i want to closeif (item.visa_req === "not_required" && !updatedHiddenFields.includes(field)) {
updatedHiddenFields.push(field);
setHiddenFields(updatedHiddenFields);
} else if (item.visa_req === "required") {
updatedHiddenFields = updatedHiddenFields.filter(f => f !== field);
setHiddenFields(updatedHiddenFields);
}
});
}
}, [watching]);
React.useEffect(() => {
const fieldKeys = [
a.b.0.min_validity_days,a.b.0.min_validity_ref];
setHiddenFields(watchingValidity ? updatedHiddenFields.filter(f => !fieldKeys.includes(f)) : [...updatedHiddenFields, ...fieldKeys]);
}, [watchingValidity]);
when one value changes i dont want to update the whole form. i want to update just one field. thats why its working so slowly.
any solution ideas??
watchin a.b has also the same effect as watching a.b.${index}.visa_req
