33 lines
685 B
TypeScript
33 lines
685 B
TypeScript
import React, {
|
|
DependencyList,
|
|
EffectCallback,
|
|
useEffect,
|
|
useRef,
|
|
} from "react";
|
|
|
|
/**
|
|
* React.useEffect, except that it never runs on mount.
|
|
* This is emulating the componentDidUpdate lifecycle function.
|
|
*/
|
|
export const useEffectExceptOnMount = (
|
|
effect: EffectCallback,
|
|
dependencies?: DependencyList
|
|
): void => {
|
|
const mounted = useRef(false);
|
|
useEffect(() => {
|
|
if (mounted.current) {
|
|
const unmount = effect();
|
|
return () => unmount && unmount();
|
|
} else {
|
|
mounted.current = true;
|
|
}
|
|
}, dependencies);
|
|
|
|
//Reset on unmount for the next mount.
|
|
useEffect(() => {
|
|
return () => {
|
|
mounted.current = false;
|
|
};
|
|
}, []);
|
|
};
|