优化
This commit is contained in:
26
client/shared/hooks/factory/createUpdateEffect.ts
Normal file
26
client/shared/hooks/factory/createUpdateEffect.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useRef } from 'react';
|
||||
import type { useEffect, useLayoutEffect } from 'react';
|
||||
|
||||
// Reference: https://github.com/alibaba/hooks/blob/master/packages/hooks/src/createUpdateEffect/index.ts
|
||||
|
||||
type EffectHookType = typeof useEffect | typeof useLayoutEffect;
|
||||
|
||||
export const createUpdateEffect: (hook: EffectHookType) => EffectHookType =
|
||||
(hook) => (effect, deps) => {
|
||||
const isMounted = useRef(false);
|
||||
|
||||
// for react-refresh
|
||||
hook(() => {
|
||||
return () => {
|
||||
isMounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
hook(() => {
|
||||
if (!isMounted.current) {
|
||||
isMounted.current = true;
|
||||
} else {
|
||||
return effect();
|
||||
}
|
||||
}, deps);
|
||||
};
|
||||
Reference in New Issue
Block a user