Skip to content

Instantly share code, notes, and snippets.

@mkhoussid
Created November 16, 2020 08:45
Show Gist options
  • Save mkhoussid/c08d0f0dbf597422559910c2fdc60d42 to your computer and use it in GitHub Desktop.
Save mkhoussid/c08d0f0dbf597422559910c2fdc60d42 to your computer and use it in GitHub Desktop.
useComponentWillMount ReactJS hook
// NOTE: This does NOT work on NextJS: https://github.com/vercel/next.js/discussions/19204
// Adapted from here: https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks#comment101488609_56818036
const useComponentWillMount = (func: (...params: any[]) => any): void => {
const willMount = useRef(true);
useEffect(() => {
// invert flag to ensure `func` does not run twice after mount
willMount.current = false;
}, []);
if (willMount.current) func();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment