'Difference between Ant Design form.setFieldsValue and initialValues prop

As the title states. What is the difference between the two?

1.

import { Form } from 'antd';

const Components = () => {
  const [form] = Form.useForm();
  form.setFieldsValue({ ... });

  return (
    <Form form={form}>
      ...
    </Form>
  );
}
import { Form } from 'antd';

const Components = () => {
  return (
    <Form initialValues={{ ... }}>
      ...
    </Form>
  );
}


Solution 1:[1]

setFieldValues is good for on-demand setting of values. For example, if there was a "Default" button on your form that sets all the values back to some default. The problem with using setFieldValues on form, is that if you are passing props down that change or a function prop, the setFieldValues will be called over and over again when props refresh in the app. This can cause the form to reset to the values in setFieldValues randomly while the user has the form up.

initialValues only sets the initial values when the form initializes and does not have the same issue as stated above, so its ideal for setting up a form with initial values while having props that may be refreshing or changing. This causes your form to behave well and not change on the user until the form is destroyed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronnie