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