This is a behaviour from React 18 itself when you are in strict mode in development
. The core team is trying to preserve components' state
even after unmount
. useEffect
getting called twice is related to this feature. Here is an overview of what they say in the doc:
In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state.
With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component.
There is a discussion going on on how to deal with this behaviour. To know more about it you can watch this YouTube Video.
In most cases you don't have to worry about it, as the problem goes away in production
. However, you can use a boolean ref
using useRef
to add some additional controls, for example in your case like so:
import { useState, useEffect, useRef } from "react";
const Counter = () => {
const firstRenderRef = useRef(true);
const [count, setCount] = useState(5);
useEffect(() => {
if(firstRenderRef.current){
firstRenderRef.current = false;
return;
}
console.log("rendered");
console.log(count);
}, [count]);
return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount( count + 1 )}> click to increase </button>
</div>
);
};
export default Counter;
console.log("rendered")
twice. Are you checking it orconsole.log(count)
console.log("component rendered")
just calls once but Theconsole.log("useEffect rendered")
calls twice andconsole.log(count)
is so onproduction
build of your project. useEffect being run twice is intended behavior of react in a development build.