Sometimes, we may want to make our useEffect
callback not run on initial render.
In this article, we’ll look at how to make the React useEffect
callback not run on initial render.
Store the Render State in a Ref
We can create a hook to check whether the first render is done before running the code we want.
To do this, we write:
import React, { useEffect, useRef, useState } from "react";
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) {
func();
} else {
didMount.current = true;
}
}, deps);
};
export default function App() {
const [count, setCount] = useState(0);
useDidMountEffect(() => {
console.log("second render");
});
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p>{count}</p>
</div>
);
}
We create the useDidMountEffect
hook to track whether the first render is done.
We do this with the didMount
ref.
We have the useEffect
hook that runs on when the deps
array is changed.
If it’s the first render, we set didMount.current
to true
.
Otherwise, we run the func
function.
In App
, we have the count
state which is updated when we click on the increment button.
We also pass a callback to the useDidMountEffect
hook which we created.
When we click on the increment button, we see 'second render'
logged after the first render.
Conclusion
We can make the React useEffect
callback not run on the first render by creating a ref that keeps track of whether the first render is done.
Then we can check the ref’s value to see when the first render is done and run the function we want when the first render is done.