diff --git a/src/common/anim/Animator.tsx b/src/common/anim/Animator.tsx index 1bb7aa4..2c68587 100644 --- a/src/common/anim/Animator.tsx +++ b/src/common/anim/Animator.tsx @@ -9,7 +9,7 @@ import { } from "react"; import "@src/common/anim/Animator.scss"; -import { useEffectRefsPopulated } from "@src/common/hooks/useEffectRefsPopulated"; +import { useRefsPopulatedEffect } from "@src/common/hooks/useRefsPopulatedEffect"; import { useCallback } from "react"; type AnimationContext = { @@ -121,7 +121,7 @@ export function Anim( const selfRef = useRef(null); const animationState = useContext(animContext); - useEffectRefsPopulated(() => { + useRefsPopulatedEffect(() => { const setups = props.setup(selfRef.current!); const anims = setups @@ -168,7 +168,7 @@ export function Anim( anims.forEach((anim) => anim.cancel()); }; - }, [selfRef.current]); + }, [selfRef]); return (
diff --git a/src/common/hooks/useEffectRefsPopulated.ts b/src/common/hooks/useEffectRefsPopulated.ts deleted file mode 100644 index de63a1c..0000000 --- a/src/common/hooks/useEffectRefsPopulated.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { useState } from "react"; -import { DependencyList, EffectCallback, useEffect } from "react"; - -export function useEffectRefsPopulated( - effect: EffectCallback, - deps?: DependencyList -): void { - const [isFirstRender, setIsFirstRender] = useState(true); - - useEffect(() => { - if (isFirstRender) { - setIsFirstRender(false); - - return; - } - - effect(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, deps); -} diff --git a/src/common/hooks/useRefsPopulatedEffect.ts b/src/common/hooks/useRefsPopulatedEffect.ts new file mode 100644 index 0000000..9ceff73 --- /dev/null +++ b/src/common/hooks/useRefsPopulatedEffect.ts @@ -0,0 +1,32 @@ +import { useRef } from "react"; +import { EffectCallback, useEffect } from "react"; + +export function useRefsPopulatedEffect( + callback: EffectCallback, + refs: React.MutableRefObject[] +) { + const refData = useRef({ + intervalIdx: 0, + effectRan: false, + cleanup: (() => {}) as ReturnType, + }); + + useEffect(() => { + if (!refData.current.effectRan) { + refData.current.intervalIdx = setInterval(() => { + if (!refData.current.effectRan && refs.every((ref) => ref.current)) { + refData.current.cleanup = callback(); + refData.current.effectRan = true; + clearInterval(refData.current.intervalIdx); + } + }, 1); + } + + return () => { + clearInterval(refData.current.intervalIdx); + // eslint-disable-next-line react-hooks/exhaustive-deps + refData.current.cleanup?.(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, refs); +}