Skip to content

Instantly share code, notes, and snippets.

@ajitid
Last active May 17, 2022 12:12
Show Gist options
  • Save ajitid/0a14f5fa3be220fda345fe86eda8c435 to your computer and use it in GitHub Desktop.
Save ajitid/0a14f5fa3be220fda345fe86eda8c435 to your computer and use it in GitHub Desktop.
`useEffectOnce` for React v18 (TypeScript)

Inspired from this blog post. If you want to change return type from void to unknown, be my guest.

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