How can we make React useEffect avoiding execution on very first render?

React useEffect always runs after the component mounts for very first time, irrespective of change in the state variable’s value. Let’s discuss, how can we avoid this. Before going through the solution below, I would suggest you to try to solve it by yourself.

import { React, useState, useEffect } from "react";

export default function App(){
    const [count, setCount] = useState(0);
    const [isMountedAfterFirstRender, setIsMountedAfterFirstRender] = useState(false);

    useEffect(()=>{
        // This block will only run on stateVar change, not on initial render
        if(isMountedAfterFirstRender){
            console.log("Count =", count);
        } else{
            setIsMountedAfterFirstRender(true);
        }
    }, [count]);

    return (
        <>
            <h1>Count = {count}</h1>
            <button onClick={()=>setCount(count+1)}>count + 1</button>
        </>
    );
}

In this case, we only want the log of count value on the count increment event only, so the isMountedAfterFirstRender variable comes into play to avoid useEffect getting triggered on the very first render. isMountedAfterFirstRender as the name suggests keeps track of whether the component has completed the first render. As the value of this variable is false on very first render it avoids the logging and sets its value to true via code in else block, so that on subsequent renders logging occur based on the count variable variation. As the value of isMountedAfterFirstRender is set to true, due to change in state the component re-renders but this time it doesn’t log instead of being isMountedAfterFirstRender = true, because the value of count has not been changed. The first time value of count was unchanged, but useEffect always runs after the component mounts for very first time, irrespective of change in the state variable’s value. Now onwards, whenever the button (count + 1) will be clicked the logging will happen. Means, on the initial render, the logging is skipped. Subsequent renders will log the count only when count changes.

There can be other approaches to this as well. I would appreciate other solutions as well, which you can email me here.