Skip to content

Instantly share code, notes, and snippets.

@dantldev
Last active April 3, 2022 17:38
Show Gist options
  • Save dantldev/33c3ef520562c5bb8924984363d26ee0 to your computer and use it in GitHub Desktop.
Save dantldev/33c3ef520562c5bb8924984363d26ee0 to your computer and use it in GitHub Desktop.
A custom hook to run a callback on react component first render without any dependency issue
import { useEffect, useState } from "react";
/**
* This hook runs a callback when a component is mounted.
*/
export const useComponentFirstRender = (callback: Function) => {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
if (isMounted) {
console.log("Component mounted!");
callback();
} else {
setIsMounted(true);
}
}, [isMounted, callback]);
}
// example of use
export const MyComponent = () => {
useComponentFirstRender(() => {
someExpensiveFunction();
// you can set state or do anything here, it doesnt matter.
});
return <p>My cool component </p>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment