I have a counter and set console.log
on useEffect
to log every change in my state
but the useEffect
calls twice!!!!
import { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(5);
useEffect(() => {
console.log("rendered");
console.log(count);
}, [count]);
console.log("rendered");
return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount(count 1)}> click to increase </button>
</div>
);
};
export default Counter;
Edit: My react version is "18.1.0"
CodePudding user response:
This is a problem from React 18 itself when you are in strict mode in development
. Basically the core team is trying to perverse components' state even after unmount in React 18. useEffect
getting called twice is related to this feature. It's under discussion on how to solve this. 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 mode
, after you build
your project. However, if something not going well for you even in production
, for now you can avoid it with a boolean ref
using useRef
, 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;