Commit c6f644f
fix: Call onChange with initial state in useEffect for FormSpy
Fixes #809
Problem:
When using FormSpy with an onChange callback that calls setState
in a parent component, React throws a warning:
'Cannot update a component while rendering a different component'
Additionally, the current implementation doesn't call onChange with
the initial form state because the shallowEqual check in the subscription
callback prevents it (initial state === subscribed state).
Root Cause:
1. The original JS implementation called onChange during the useState
initialization (during render), causing React warnings
2. The current TS implementation fixed the warning but broke onChange
for initial state due to shallowEqual check
Solution:
Added a separate useEffect (with empty deps) that explicitly calls
onChange with the initial state after the first render completes.
This ensures:
- onChange is called AFTER render (no React warnings)
- onChange IS called with initial state (expected behavior)
- Subsequent changes still trigger onChange via subscription
Changes:
- src/useFormState.ts:
- Added new useEffect to call onChange(state) after initial render
- Runs only once with empty dependency array
- Uses onChangeRef to always call the latest onChange
Impact:
✅ Fixes 'Cannot update while rendering' warning
✅ onChange called with initial state as expected
✅ FormSpy tests pass
✅ No breaking changes
Originally reported in issue #809, attempted fix in PR #965 (closed).
Co-authored-by: Jinxuan Zhu <zhujinxuan@users.noreply.github.com>1 parent e474d2b commit c6f644f
1 file changed
+12
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
20 | 20 | | |
21 | 21 | | |
22 | 22 | | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
23 | 26 | | |
24 | 27 | | |
25 | 28 | | |
26 | 29 | | |
27 | | - | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
28 | 39 | | |
29 | 40 | | |
30 | 41 | | |
| |||
0 commit comments