-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathuseLayoutEffect.ts
More file actions
43 lines (37 loc) · 1.01 KB
/
useLayoutEffect.ts
File metadata and controls
43 lines (37 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import * as React from 'react';
import canUseDom from '../Dom/canUseDom';
/**
* Wrap `React.useLayoutEffect` which will not throw warning message in test env
*/
const useInternalLayoutEffect =
process.env.NODE_ENV !== 'test' && canUseDom()
? React.useLayoutEffect
: React.useEffect;
const useLayoutEffect = (
callback: (mount: boolean) => void | VoidFunction,
deps?: React.DependencyList,
) => {
const firstMountRef = React.useRef<boolean>(true);
useInternalLayoutEffect(() => {
return callback(firstMountRef.current);
}, deps);
// We tell react that first mount has passed
useInternalLayoutEffect(() => {
firstMountRef.current = false;
return () => {
firstMountRef.current = true;
};
}, []);
};
export const useLayoutUpdateEffect: typeof React.useEffect = (
callback,
deps,
) => {
useLayoutEffect(firstMount => {
if (!firstMount) {
return callback();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
};
export default useLayoutEffect;