Skip to content

Comments

fix: prevent duplicate subscription trigger in setValue#13209

Merged
bluebill1049 merged 2 commits intoreact-hook-form:masterfrom
constantly-dev:fix/13206-subscription-triggers-twice
Dec 20, 2025
Merged

fix: prevent duplicate subscription trigger in setValue#13209
bluebill1049 merged 2 commits intoreact-hook-form:masterfrom
constantly-dev:fix/13206-subscription-triggers-twice

Conversation

@constantly-dev
Copy link
Contributor

Description

Closes #13206

This PR fixes a bug where the subscription callback triggers twice when a field is both watched (via useWatch or watch) and subscribed to.

Problem

In the setValue function within createFormControl.ts, the state update notification (_subjects.state.next) was being triggered twice under specific conditions:

  1. First, inside the if (isWatched(name, _names)) block.
  2. Second, unconditionally at the end of the function.

This caused subscribers to receive duplicate events for a single value change.

Solution

I refactored the notification logic in setValue to use an if/else block. Now, _subjects.state.next is guaranteed to be called exactly once:

  • If Watched: Sends the update including the full form state and values.
  • If Not Watched: Sends the standard update logic.

Testing

I have added a reproduction test case in src/__tests__/issue-13206.test.tsx.
This test spies on control._subjects.state.next to verify that it is invoked exactly once when setValue is called on a watched field.

// Key verification logic in the test
expect(nextSpy).toHaveBeenCalledTimes(1);

Note

I created a separate test file (src/tests/issue-13206.test.tsx) to isolate the reproduction case and ensure clarity for this specific issue.

If you prefer, I am happy to:

  • Move this test case into src/tests/useForm/setValue.test.tsx
  • Or remove the file entirely if the existing regression tests are considered sufficient.

@bluebill1049 bluebill1049 merged commit e45b4cb into react-hook-form:master Dec 20, 2025
6 checks passed
@constantly-dev
Copy link
Contributor Author

@bluebill1049

Thanks for the merge!
Just wanted to double-check if it is okay to keep src/tests/issue-13206.test.tsx as a standalone file?

Thanks again!

@bluebill1049
Copy link
Member

bluebill1049 commented Dec 20, 2025

oh thanks for the fix, let's move to setValue.test plz

@constantly-dev
Copy link
Contributor Author

oh thanks for the fix, let's move to setValue.test plz

@bluebill1049
Thanks for the feedback! I've moved the test case to src/__tests__/useForm/setValue.test.tsx as requested.
Here is the follow-up PR: Link

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: subscription triggers twice when field is also being watched

2 participants