@@ -3,12 +3,20 @@ import { FieldContext } from '.';
33import warning from 'rc-util/lib/warning' ;
44import { HOOK_MARK } from './FieldContext' ;
55import type { InternalFormInstance , NamePath , Store } from './interface' ;
6- import { useState , useContext , useEffect , useRef } from 'react' ;
6+ import { useState , useContext , useEffect , useRef , useMemo } from 'react' ;
77import { getNamePath , getValue } from './utils/valueUtil' ;
88
99type ReturnPromise < T > = T extends Promise < infer ValueType > ? ValueType : never ;
1010type GetGeneric < TForm extends FormInstance > = ReturnPromise < ReturnType < TForm [ 'validateFields' ] > > ;
1111
12+ function stringify ( value : any ) {
13+ try {
14+ return JSON . stringify ( value ) ;
15+ } catch ( err ) {
16+ return Math . random ( ) ;
17+ }
18+ }
19+
1220function useWatch <
1321 TDependencies1 extends keyof GetGeneric < TForm > ,
1422 TForm extends FormInstance ,
@@ -52,8 +60,10 @@ function useWatch<ValueType = Store>(dependencies: NamePath, form?: FormInstance
5260
5361function useWatch ( dependencies : NamePath = [ ] , form ?: FormInstance ) {
5462 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 ;
5767
5868 const fieldContext = useContext ( FieldContext ) ;
5969 const formInstance = ( form as InternalFormInstance ) || fieldContext ;
@@ -83,7 +93,10 @@ function useWatch(dependencies: NamePath = [], form?: FormInstance) {
8393
8494 const cancelRegister = registerWatch ( store => {
8595 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 ) {
87100 setValue ( newValue ) ;
88101 }
89102 } ) ;
0 commit comments