Skip to content

Conversation

@Han5991
Copy link
Contributor

@Han5991 Han5991 commented Apr 25, 2025

🐞 fix #12772 reset form

Problem:

Previously, the useWatch hook could sometimes fail to immediately reflect the form values after a reset operation, particularly when defaultValue was provided and used in conjunction with Controller. This could lead to a scenario where a user had to trigger the reset action twice for the useWatch value to update correctly to the default value

The likely cause was related to how defaultValue was managed and included in the dependency array of useDeepEqualEffect. When the form was reset, the internal handling of default values could potentially cause useWatch's internal subscription to briefly become out of sync with the form's actual state, as the useDeepEqualEffect might trigger a re-subscription based on a perceived change in the defaultValue object reference or content during the reset process. This timing mismatch meant the hook might not pick up the newly reset value immediately.

Solution:

This change modifies how defaultValue is handled within the useWatch hook. Instead of including defaultValue in the useEffect dependency array (previously via useDeepEqualEffect), defaultValue is now stored in a useRef.

By storing defaultValue in a useRef, its value can be accessed within the effect callback without being part of the dependency array.

Impact:

This ensures that the subscription established by useWatch is not unnecessarily torn down and re-established solely due to potential changes or re-creations of the defaultValue object during the form reset process. The subscription remains stable, allowing useWatch to reliably pick up and reflect the form's state, including the correctly applied default values, immediately after reset is called. This resolves the issue where a second reset was sometimes required.

…faultValue and optimize effect dependencies
@bluebill1049
Copy link
Member

oh nice, any chance we could follow with a unit test for this? just so this can be prevented next time.

@Han5991
Copy link
Contributor Author

Han5991 commented Apr 27, 2025

oh nice, any chance we could follow with a unit test for this? just so this can be prevented next time.

Of course, I'll get a unit test ready to make sure this doesn't happen again.

bluebill1049
bluebill1049 previously approved these changes Apr 27, 2025
@bluebill1049 bluebill1049 merged commit 5f4f050 into react-hook-form:master Apr 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

issue: reset form

2 participants