@@ -3,12 +3,20 @@ import { FieldContext } from '.';
3
3
import warning from 'rc-util/lib/warning' ;
4
4
import { HOOK_MARK } from './FieldContext' ;
5
5
import type { InternalFormInstance , NamePath , Store } from './interface' ;
6
- import { useState , useContext , useEffect , useRef } from 'react' ;
6
+ import { useState , useContext , useEffect , useRef , useMemo } from 'react' ;
7
7
import { getNamePath , getValue } from './utils/valueUtil' ;
8
8
9
9
type ReturnPromise < T > = T extends Promise < infer ValueType > ? ValueType : never ;
10
10
type GetGeneric < TForm extends FormInstance > = ReturnPromise < ReturnType < TForm [ 'validateFields' ] > > ;
11
11
12
+ function stringify ( value : any ) {
13
+ try {
14
+ return JSON . stringify ( value ) ;
15
+ } catch ( err ) {
16
+ return Math . random ( ) ;
17
+ }
18
+ }
19
+
12
20
function useWatch <
13
21
TDependencies1 extends keyof GetGeneric < TForm > ,
14
22
TForm extends FormInstance ,
@@ -52,8 +60,10 @@ function useWatch<ValueType = Store>(dependencies: NamePath, form?: FormInstance
52
60
53
61
function useWatch ( dependencies : NamePath = [ ] , form ?: FormInstance ) {
54
62
const [ value , setValue ] = useState < any > ( ) ;
55
- const valueCacheRef = useRef < any > ( ) ;
56
- valueCacheRef . current = value ;
63
+
64
+ const valueStr = useMemo ( ( ) => stringify ( value ) , [ value ] ) ;
65
+ const valueStrRef = useRef ( valueStr ) ;
66
+ valueStrRef . current = valueStr ;
57
67
58
68
const fieldContext = useContext ( FieldContext ) ;
59
69
const formInstance = ( form as InternalFormInstance ) || fieldContext ;
@@ -83,7 +93,10 @@ function useWatch(dependencies: NamePath = [], form?: FormInstance) {
83
93
84
94
const cancelRegister = registerWatch ( store => {
85
95
const newValue = getValue ( store , namePathRef . current ) ;
86
- if ( valueCacheRef . current !== newValue ) {
96
+ const nextValueStr = stringify ( newValue ) ;
97
+
98
+ // Compare stringify in case it's nest object
99
+ if ( valueStrRef . current !== nextValueStr ) {
87
100
setValue ( newValue ) ;
88
101
}
89
102
} ) ;
0 commit comments