Inspired from this blog post. If you want to change return type from void
to unknown
, be my guest.
Last active
May 17, 2022 12:12
-
-
Save ajitid/0a14f5fa3be220fda345fe86eda8c435 to your computer and use it in GitHub Desktop.
`useEffectOnce` for React v18 (TypeScript)
This file contains hidden or 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
import { useEffect, useInsertionEffect, useRef } from "react"; | |
const useEffectOnce = (effect: () => void | (() => void)) => { | |
const isEffectAlreadyCalledRef = useRef(false); | |
const isActualUnmountRef = useRef(false); | |
const cleanupRef = useRef(() => {}); | |
useInsertionEffect(() => { | |
return () => { | |
isActualUnmountRef.current = true; | |
}; | |
}, []); | |
useEffect(() => { | |
if (!isEffectAlreadyCalledRef.current) { | |
isEffectAlreadyCalledRef.current = true; | |
let cleanup = effect(); | |
if (typeof cleanup === "function") { | |
cleanupRef.current = cleanup; | |
} | |
} | |
return () => { | |
if (isActualUnmountRef.current) { | |
cleanupRef.current(); | |
} | |
}; | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment