Skip to content

useFirstRender

React hook to detect if it is the first render of a component.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useFirstRender
sh
npx @novajslabs/cli add useFirstRender
sh
pnpm dlx @novajslabs/cli add useFirstRender

Or copy and paste the code into your project:

ts
import { useRef, useEffect } from "react";

export const useFirstRender = () => {
  const firstRender = useRef(true);

  useEffect(() => {
    firstRender.current = false;
  }, []);

  return firstRender.current;
};
js
import { useRef, useEffect } from "react";

export const useFirstRender = () => {
  const firstRender = useRef(true);

  useEffect(() => {
    firstRender.current = false;
  }, []);

  return firstRender.current;
};

Requirements

React 16.8 or higher

Return values

firstRender

Type: boolean

Indicates whether it is the first render of a component (true) or not (false).

Example

tsx
import { useFirstRender } from "./hooks/useFirstRender";
import { useReducer } from "react";

const App = () => {
  const firstRender = useFirstRender();
  const [count, rerender] = useReducer((x) => x + 1, 1);

  return (
    <>
      <h2>First render? {firstRender ? "Yes" : "No"}</h2>
      <button onClick={rerender}>re-render</button>
      <p>Render Count: {count}</p>
    </>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Initialize data fetching only on the first render
  • Prevent animations or transitions from running on the initial render
  • Configure or reset timers only on the first render

Released under the MIT License.