Last active
April 3, 2022 17:38
-
-
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
This file contains 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, 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