Skip to content

How to implement real-time validation without causing re-renders? #197

@HyeongJunJeon

Description

@HyeongJunJeon

Environment

  • @autoform/react: 4.0.0
  • @autoform/yup: 3.0.0
  • react-hook-form: 7.68.0

Context

I want to implement real-time validation in AutoForm. I need an isValid state to enable/disable the submit button.

Since @autoform/react doesn't support the mode option, I implemented it manually using onFormInit and form.watch():

export function useAutoFormValidation<T extends FieldValues>(
  schemaProvider: SchemaProvider
) {
  const [isValid, setIsValid] = useState(false);

  const handleFormInit = useCallback(
    (form: UseFormReturn<T>) => {
      const subscription = form.watch((_, { name }) => {
        if (!name) return;
        const allValues = form.getValues();
        const result = schemaProvider.validateSchema(allValues);
        
        if (result.success) {
          form.clearErrors(name);
        } else {
          const fieldError = result.errors.find(
            (err) => err.path.join(".") === name
          );
          fieldError
            ? form.setError(name, { message: fieldError.message })
            : form.clearErrors(name);
        }
        
        setIsValid(result.success);
      });

      return () => subscription.unsubscribe();
    },
    [schemaProvider]
  );

  return { isValid, handleFormInit };
}

Problem

This approach causes all input components to re-render on every keystroke, resulting in poor UX (input lag).

Question

Is there a recommended way to implement real-time validation in AutoForm? I'd like to achieve the following while minimizing re-renders:

  1. Display field-level error messages in real-time
  2. Enable/disable submit button based on the form's isValid state
    Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions