1 | import { useLayoutEffect, useRef } from 'react';
|
2 | /**
|
3 | * Runs a layout effect only when the dependencies have changed, skipping the
|
4 | * initial "on mount" run. Caution, if the dependency list never changes,
|
5 | * the effect is **never run**
|
6 | *
|
7 | * ```ts
|
8 | * const ref = useRef<HTMLInput>(null);
|
9 | *
|
10 | * // focuses an element only if the focus changes, and not on mount
|
11 | * useUpdateLayoutEffect(() => {
|
12 | * const element = ref.current?.children[focusedIdx] as HTMLElement
|
13 | *
|
14 | * element?.focus()
|
15 | *
|
16 | * }, [focusedIndex])
|
17 | * ```
|
18 | * @param effect An effect to run on mount
|
19 | *
|
20 | * @category effects
|
21 | */
|
22 |
|
23 | function useUpdateLayoutEffect(fn, deps) {
|
24 | var isFirst = useRef(true);
|
25 | useLayoutEffect(function () {
|
26 | if (isFirst.current) {
|
27 | isFirst.current = false;
|
28 | return;
|
29 | }
|
30 |
|
31 | return fn();
|
32 | }, deps);
|
33 | }
|
34 |
|
35 | export default useUpdateLayoutEffect; |
\ | No newline at end of file |