File tree Expand file tree Collapse file tree 2 files changed +44
-11
lines changed Expand file tree Collapse file tree 2 files changed +44
-11
lines changed Original file line number Diff line number Diff line change @@ -4,30 +4,39 @@ import canUseDom from '../Dom/canUseDom';
4
4
/**
5
5
* Wrap `React.useLayoutEffect` which will not throw warning message in test env
6
6
*/
7
- const useLayoutEffect =
7
+ const useInternalLayoutEffect =
8
8
process . env . NODE_ENV !== 'test' && canUseDom ( )
9
9
? React . useLayoutEffect
10
10
: React . useEffect ;
11
11
12
- export default useLayoutEffect ;
13
-
14
- export const useLayoutUpdateEffect : typeof React . useEffect = (
15
- callback ,
16
- deps ,
12
+ const useLayoutEffect = (
13
+ callback : ( mount : boolean ) => void | VoidFunction ,
14
+ deps ?: React . DependencyList ,
17
15
) => {
18
16
const firstMountRef = React . useRef ( true ) ;
19
17
20
- useLayoutEffect ( ( ) => {
21
- if ( ! firstMountRef . current ) {
22
- return callback ( ) ;
23
- }
18
+ useInternalLayoutEffect ( ( ) => {
19
+ return callback ( firstMountRef . current ) ;
24
20
} , deps ) ;
25
21
26
22
// We tell react that first mount has passed
27
- useLayoutEffect ( ( ) => {
23
+ useInternalLayoutEffect ( ( ) => {
28
24
firstMountRef . current = false ;
29
25
return ( ) => {
30
26
firstMountRef . current = true ;
31
27
} ;
32
28
} , [ ] ) ;
33
29
} ;
30
+
31
+ export const useLayoutUpdateEffect : typeof React . useEffect = (
32
+ callback ,
33
+ deps ,
34
+ ) => {
35
+ useLayoutEffect ( firstMount => {
36
+ if ( ! firstMount ) {
37
+ return callback ( ) ;
38
+ }
39
+ } , deps ) ;
40
+ } ;
41
+
42
+ export default useLayoutEffect ;
Original file line number Diff line number Diff line change @@ -343,6 +343,30 @@ describe('hooks', () => {
343
343
expect ( errorSpy ) . not . toHaveBeenCalled ( ) ;
344
344
errorSpy . mockRestore ( ) ;
345
345
} ) ;
346
+
347
+ it ( 'can get mount state' , ( ) => {
348
+ const Demo = ( ) => {
349
+ const timesRef = React . useRef ( 0 ) ;
350
+ const [ , forceUpdate ] = React . useState ( 0 ) ;
351
+
352
+ useLayoutEffect ( firstMount => {
353
+ if ( timesRef . current === 0 ) {
354
+ expect ( firstMount ) . toBeTruthy ( ) ;
355
+ forceUpdate ( 1 ) ;
356
+ } else {
357
+ expect ( firstMount ) . toBeFalsy ( ) ;
358
+ forceUpdate ( 2 ) ;
359
+ }
360
+
361
+ timesRef . current += 1 ;
362
+ } ) ;
363
+
364
+ return < p > { timesRef . current } </ p > ;
365
+ } ;
366
+
367
+ const { container } = render ( < Demo /> ) ;
368
+ expect ( container . querySelector ( 'p' ) . textContent ) . toEqual ( '2' ) ;
369
+ } ) ;
346
370
} ) ;
347
371
348
372
describe ( 'useState' , ( ) => {
You can’t perform that action at this time.
0 commit comments