Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created May 5, 2022 18:46
Show Gist options
  • Save fostyfost/7a17a97375479d992f556b8e352b92ae to your computer and use it in GitHub Desktop.
Save fostyfost/7a17a97375479d992f556b8e352b92ae to your computer and use it in GitHub Desktop.
Use Effect Once
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