UNPKG

845 BJavaScriptView Raw
1import { useLayoutEffect, useRef } from 'react';
2
3/**
4 * Runs a layout 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 * useUpdateLayoutEffect(() => {
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 */
23function useUpdateLayoutEffect(fn, deps) {
24 const isFirst = useRef(true);
25 useLayoutEffect(() => {
26 if (isFirst.current) {
27 isFirst.current = false;
28 return;
29 }
30 return fn();
31 }, deps);
32}
33export default useUpdateLayoutEffect;
\No newline at end of file