GoScrobble/web/node_modules/@restart/hooks/esm/useUpdateEffect.js

35 lines
815 B
JavaScript
Raw Permalink Normal View History

2022-04-25 02:47:15 +00:00
import { useEffect, useRef } from 'react';
/**
* Runs an effect only when the dependencies have changed, skipping the
* initial "on mount" run. Caution, if the dependency list never changes,
* the effect is **never run**
*
* ```ts
* const ref = useRef<HTMLInput>(null);
*
* // focuses an element only if the focus changes, and not on mount
* useUpdateEffect(() => {
* const element = ref.current?.children[focusedIdx] as HTMLElement
*
* element?.focus()
*
* }, [focusedIndex])
* ```
* @param effect An effect to run on mount
*
* @category effects
*/
function useUpdateEffect(fn, deps) {
var isFirst = useRef(true);
useEffect(function () {
if (isFirst.current) {
isFirst.current = false;
return;
}
return fn();
}, deps);
}
export default useUpdateEffect;