useIsFirstRender
React hook that returns true if the component is the first render
Example
import { useState } from "react";
import useIsFirstRender from "@/hooks/useIsFirstRender";
export default function UseIsFirstRenderExample() {
const isFirstRender = useIsFirstRender();
const [count, setCount] = useState(0);
return (
<div className="text-ctp-text">
<p>Is first render: {isFirstRender ? "yes" : "no"}</p>
<p>Count: {count}</p>
<button
className="rounded bg-ctp-blue px-4 py-2 text-ctp-base"
onClick={() => setCount(count + 1)}
>
Increment
</button>
</div>
);
}
Code
import { useRef } from "react";
/**
* React hook that returns true if the component is the first render
* @returns {boolean} true if the component is the first render
*/
export default function useIsFirstRender(): boolean {
const renderRef = useRef(true);
if (renderRef.current === true) {
renderRef.current = false;
return true;
}
return renderRef.current;
}