Check if a component is rendering for the first time.
import { useRef } from 'react';
export function useIsFirstRender(): boolean {
const isFirst = useRef(true);
if (isFirst.current) {
isFirst.current = false;
return true;
}
return false;
}Sometimes in React, you want to run logic only on the first render of a component — not on subsequent updates. The useIsFirstRender hook provides a clean way to detect the initial render.
import { useRef } from 'react';
export function useIsFirstRender(): boolean {
const isFirst = useRef(true);
if (isFirst.current) {
isFirst.current = false;
return true;
}
return false;
}
function ExampleComponent() {
const isFirstRender = useIsFirstRender();
useEffect(() => {
if (!isFirstRender) {
console.log("Component updated (not initial render)");
}
}, [someState]);
return (
<div>
{isFirstRender ? "First render!" : "Rendered again!"}
</div>
);
}
Useful if you want to skip running effects on initial render.
The useIsFirstRender hook is a lightweight and powerful utility that helps you distinguish between initial and subsequent renders in React — giving you more control over when to trigger logic.