useFirstRender() - Building a custom React hook

Building a custom React hook which allows us to check whether the component is currently on the first render.


React state management is a huge challenge in itself and it keeps getting more and more complicated as the project size grows. Often, we encounter situtations where we wish for a specific behaviour to work on the first render of a component but not afterwards ever. You might think using a simple useEffect would solve this problem as

useEffect(() => {
   // Only executes on first render
}, []); // empty dependency array

and you would be right about this. The above snippet will work in most such situations where a specific behaviour is required on first render.

However things are not always this simple. Often working on large projects with hundreds of states and functionalities, things tend to go out of hands. So for these situations, we can build a simple short custom hook, that will do the trick for us.

Building the custom hook

Custom hooks are quite handy as they allow us to interact with our components and trigger some specific behaviour in them. Read more about Custom hooks here.

We are going to use the advantage of refs here to know whether we are in the first render here. The beauty of refs is that a change in the value of ref will not update the component, unlike state.

We use this advantage of refs to create a flag variable which stores whether we are at the first render or not, and return its value in our custom hook.

Our first render hook would look something like this

import { useRef, useEffect } from 'react';

export default function useFirstRender() {
  const firstRender = useRef(true);

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

  return firstRender.current;

We can now use it in our component as

  const isFirstRender = useFirstRender();

  useEffect(() => {
    if (isFirstRender) {
      // Will only run on first render
    // Will whenever any item in dependency array changes
  }, [isFirstRender, fetchData]);

Codesandbox Sample:

Keep this hook as a generic hook in your code repository because of its simple and versatile nature. This is most likely to come in handy when you are working with several states in a single component.

Happy Coding.