ant-design: Form.useWatch doesn't return initial values

Reproduction link

Edit on CodeSandbox

Steps to reproduce

  • Open the reproduction link and browser console there
  • You’ll see a log like form instance: John watcher: undefined

This means John value comes from useFormInstance and undefined comes from useWatch

What is expected?

I’d expect both values to be equivalent

What is actually happening?

useWatch returns undefined value for a field, but in reality it’s defined by Form’s initialValues

Environment Info
antd 5.17.3
React 18
System Mac OS
Browser Chrome

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

 const [form] = Form.useForm<{ name: string }>();
  const nameWatch = Form.useWatch('name', form);
  const nameValue = form.isFieldTouched('name') ? nameWatch : 'init';

https://stackblitz.com/edit/react-fpk9br?file=demo.tsx

The initial undefined return from Form.useWatch([], form) is understood. However, there’s a type safety issue for TypeScript users.

When using FormInstance<T>, Form.useWatch([], form) infers the return type as T, but the actual initial return value is undefined. This mismatch bypasses static checks and can lead to runtime errors.

Proposal: Could the TypeScript definition for Form.useWatch([], form) (when used with FormInstance<T>) be updated to return T | undefined?

This would accurately reflect the runtime behavior, enforce safer access patterns (?. / ?? ), and align with similar hooks in other libraries.

Thank you for considering this improvement for TypeScript users.

Using this custom hook which returns the form’s value if Form.useWatch returns undefined.

/**
* Wrapper of Form.useWatch to handle initial render race condition.
* Form.useWatch always yields undefined in the first render.
* This wrapper handles that by sending the value from form.getFieldValue if the watched value is undefined.
* This will get corrected from second render.
* @see https://github.com/ant-design/ant-design/issues/49010#issuecomment-2123979311
* @param {string|string[]} field - Field Name.
* @returns {*} Watched value
*/
export const useWatch = (...args) => {
  const form = Form.useFormInstance();
  const value = Form.useWatch(...args);
  return value !== undefined ? value : form.getFieldValue(args[0);
};
  • This method works even if form.getFieldValue doesn’t trigger a re-render because Form.useWatch triggers it.
  • The value from form.getFieldValue will only be used for the first render. As mentioned above, from the second render useWatch will give the required watched value.