Created
August 8, 2023 15:25
-
-
Save moritzsalla/0f2b841567f4fdc19f8f8246ef253759 to your computer and use it in GitHub Desktop.
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, useRef } from "react"; | |
/** | |
* A React hook that returns true if the component is being rendered for the first time. | |
* | |
* @returns boolean | |
* @example | |
* ```tsx | |
* import { useIsInitialRender } from "hooks/useIsInitialRender"; | |
* | |
* const Component = () => { | |
* const isInitialRender = useIsInitialRender(); | |
* | |
* return ( | |
* <div> | |
* {isInitialRender ? "This is the first render" : "This is not the first render"} | |
* </div> | |
* ); | |
* }; | |
*``` | |
*/ | |
export const useIsInitialRender = () => { | |
const initial = useRef(true); | |
useEffect(() => { | |
initial.current = false; | |
return () => { | |
initial.current = true; | |
}; | |
}, []); | |
return initial.current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment