perf: stabilize useConditionalField default values with useRef and replace Zod superRefine with declarative unions for performance

This commit is contained in:
Firman Ramdhani
2026-06-15 23:06:58 +07:00
parent 50cce32ada
commit f9a6519da4
3 changed files with 104 additions and 21 deletions
@@ -28,24 +28,30 @@ export default function ReactiveWatchDemo() {
department: z.string().optional(),
role: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.userType === 'CORPORATE') {
const res = taxIdValidator.safeParse(data.corporateTaxId || '');
if (!res.success) res.error.issues.forEach((i: any) => ctx.addIssue({ ...i, path: ['corporateTaxId'] }));
}
if (data.hasSpouse) {
const res = spouseNameValidator.safeParse(data.spouseName || '');
if (!res.success) res.error.issues.forEach((i: any) => ctx.addIssue({ ...i, path: ['spouseName'] }));
}
if (data.newsletter) {
const res = newsletterEmailValidator.safeParse(data.newsletterEmail || '');
if (!res.success) res.error.issues.forEach((i: any) => ctx.addIssue({ ...i, path: ['newsletterEmail'] }));
}
if (data.department) {
const res = roleValidator.safeParse(data.role || '');
if (!res.success) res.error.issues.forEach((i: any) => ctx.addIssue({ ...i, path: ['role'] }));
}
});
.and(
z.discriminatedUnion('userType', [
z.object({ userType: z.literal('PERSONAL') }),
z.object({ userType: z.literal('CORPORATE'), corporateTaxId: taxIdValidator })
])
)
.and(
z.union([
z.object({ hasSpouse: z.literal(false) }),
z.object({ hasSpouse: z.literal(true), spouseName: spouseNameValidator })
])
)
.and(
z.union([
z.object({ newsletter: z.literal(false) }),
z.object({ newsletter: z.literal(true), newsletterEmail: newsletterEmailValidator })
])
)
.and(
z.union([
z.object({ department: z.string().min(1), role: roleValidator }),
z.object({ department: z.union([z.literal(''), z.undefined(), z.null()]).optional() })
])
);
const { control, handleSubmit, setValue, unregister, clearErrors } = useForm<any>({
resolver: zodResolver(reactiveSchema as any),