Skip to content

Instantly share code, notes, and snippets.

@moritzsalla
Created August 8, 2023 15:25
Show Gist options
  • Save moritzsalla/0f2b841567f4fdc19f8f8246ef253759 to your computer and use it in GitHub Desktop.
Save moritzsalla/0f2b841567f4fdc19f8f8246ef253759 to your computer and use it in GitHub Desktop.
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