Skip to content

Commit 3e8a278

Browse files
authored
feat: export useLayoutUpdateEffect (#326)
1 parent 7c5a229 commit 3e8a278

File tree

2 files changed

+23
-20
lines changed

2 files changed

+23
-20
lines changed

src/hooks/useLayoutEffect.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,24 @@ const useLayoutEffect =
1010
: React.useEffect;
1111

1212
export default useLayoutEffect;
13+
14+
export const useLayoutUpdateEffect: typeof React.useEffect = (
15+
callback,
16+
deps,
17+
) => {
18+
const firstMountRef = React.useRef(true);
19+
20+
useLayoutEffect(() => {
21+
if (!firstMountRef.current) {
22+
return callback();
23+
}
24+
}, deps);
25+
26+
// We tell react that first mount has passed
27+
useLayoutEffect(() => {
28+
firstMountRef.current = false;
29+
return () => {
30+
firstMountRef.current = true;
31+
};
32+
}, []);
33+
};

src/hooks/useMergedState.ts

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as React from 'react';
22
import useEvent from './useEvent';
3-
import useLayoutEffect from './useLayoutEffect';
3+
import useLayoutEffect, { useLayoutUpdateEffect } from './useLayoutEffect';
44
import useState from './useState';
55

66
type Updater<T> = (
@@ -15,24 +15,6 @@ enum Source {
1515

1616
type ValueRecord<T> = [T, Source, T];
1717

18-
const useUpdateEffect: typeof React.useEffect = (callback, deps) => {
19-
const firstMountRef = React.useRef(true);
20-
21-
useLayoutEffect(() => {
22-
if (!firstMountRef.current) {
23-
return callback();
24-
}
25-
}, deps);
26-
27-
// We tell react that first mount has passed
28-
useLayoutEffect(() => {
29-
firstMountRef.current = false;
30-
return () => {
31-
firstMountRef.current = true;
32-
};
33-
}, []);
34-
};
35-
3618
/** We only think `undefined` is empty */
3719
function hasValue(value: any) {
3820
return value !== undefined;
@@ -82,7 +64,7 @@ export default function useMergedState<T, R = T>(
8264
const postMergedValue = postState ? postState(chosenValue) : chosenValue;
8365

8466
// ======================= Sync =======================
85-
useUpdateEffect(() => {
67+
useLayoutUpdateEffect(() => {
8668
setMergedValue(([prevValue]) => [value, Source.PROP, prevValue]);
8769
}, [value]);
8870

0 commit comments

Comments
 (0)