The useEffect
callback runs whenever the states we’re watching are updated, when a re-rendering is done, or when the component mounts.
However, sometimes, we may want to make it run only after the initial render is done.
In this article, we’ll look at how to make the useEffect
hook callback run only after the first render.
Make the useEffect Hook Not Run on Initial Render
We can make the useEffect
hook not run on initial render by creating a variable with useRef
hook to keep tracking of when the first render is done.
We set the variable’s value to true
initially.
Then we the component is rendered the first time, we set the variable to false
.
To do this, we write:
import { useEffect, useRef, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const firstUpdate = useRef(true);
useEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log(count);
});
return (
<div>
<button
onClick={() => {
setCount((count) => count + 1);
}}
>
increment
</button>
<p>{count}</p>
</div>
);
}
We have the count
state which is initially set to 0.
Then we have the useEffect
hook called with a callback that gets the firstUpdate.current
property.
If it’s true
, then first render isn’t done yet since we created the firstUpdate
variable with useRef
and set its current
value to true
initially.
Therefore, if it’s true
, then we set firstUpdate.current
to false
and stop running the rest of the code.
Otherwise, we log the value of count
.
We didn’t pass in a second argument into useEffect
, so the callback runs on every render.
Below that, we have a button with an onClick
prop set to a function that calls setCount
with a callback to increment count
by 1.
And below that, we show the count
value.
Now in the console, we should see that 0 isn’t logged, so we know that the code after the if
block in the useEffect
callback didn’t run during the first render.
Conclusion
To prevent the useEffect
callback code from running on initial render of a component, we can create a variable to keep track of whether the first render of a component is done.
We only proceed on running the remainder of the useEffect
callback only when the variable value indicates that the first render has been done.