Created
May 5, 2022 18:46
-
-
Save fostyfost/7a17a97375479d992f556b8e352b92ae to your computer and use it in GitHub Desktop.
Use Effect Once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useEffectOnce = (effect: EffectCallback) => { | |
const destroyFunc = useRef<ReturnType<EffectCallback>>() | |
const calledOnce = useRef(false) | |
const renderAfterCalled = useRef(false) | |
if (calledOnce.current) { | |
renderAfterCalled.current = true | |
} | |
useEffect(() => { | |
if (calledOnce.current) { | |
return | |
} | |
calledOnce.current = true | |
destroyFunc.current = effect() | |
return () => { | |
if (!renderAfterCalled.current) { | |
return | |
} | |
if (destroyFunc.current) { | |
destroyFunc.current() | |
} | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment