Search code examples
javascriptreactjstypescriptreact-final-form

React Final Form validate is not working when the validate function is outside of the react FC


I have a Form component in which I provide a validate function to it. When I define the validate function inside of the FC, it works. But when I extract that function outside of the FC, it will not be called.

This works:

import { FC } from 'react';
import { Form } from 'react-final-form';
const MyComponent: FC = () => {
  const validate = (values: ValidationValues) => { ... }

  return (
    <Form
      onSubmit={onSubmit}
      validate={validate}
    >
    ...
    </Form>
  );
}

This will not work: (validate function will not be called)

import { FC } from 'react';
import { Form } from 'react-final-form';

const validate = (values: ValidationValues) => { ... }
const MyComponent: FC = () => {
  return (
    <Form
      onSubmit={onSubmit}
      validate={validate}
    >
    ...
    </Form>
  );
}

The way to fix the issue is sth like this, but I don't understand what is the reason for this behavior:

import { FC } from 'react';
import { Form } from 'react-final-form';

const validate = (values: ValidationValues) => { ... }
const MyComponent: FC = () => {
  return (
    <Form
      onSubmit={onSubmit}
      validate={(values: ValidationValues) => validate(values)}
    >
    ...
    </Form>
  );
}

Some information about the version of the packages that I use:

react-final-form: 6.3.0
react: 16.8.6

Solution

  • The problem was that when we pass validate function which is defined inside of the react component, the validate function will be created again whenever the component is re-rendered.

    So in the case when we extract the validation, it will not be re-created again so as a result, it will not be run again after creation.