I have a counter and console.log()
in useEffect
to log every change in my state, but useEffect
is not working on the mount is called twice. I'm using React 18. Here is my project's CodeSandbox and the code below:
import { useState, useEffect } from "react"; const Counter = () => { const [count, setCount] = useState(5); useEffect(() => { console.log("rendered", count); }, [count]); return ( <div> <h1> Counter </h1> <div> {count} </div> <button onClick={() => setCount(count + 1)}> click to increase </button> </div> ); }; export default Counter;
UPDATE: Review this post and be a little wiser and please don't do this.
Use
ref
or create a customhook
without one.Since React 18, when you use
StrictMode
fordevelopment
, it is normal foruseEffect
to be called twice on mount. Here's what they have in Document:This may seem strange, but ultimately, we write better React code by caching HTTP requests and using a cleanup function when there is an issue between two calls, being bug-free, compliant with current guidelines, and compatible with future versions. Here is an example:
In this very detailed article, the React team explains
useEffect
like never before and illustrates it with examples:For your specific use case, you can leave it as is, no worries. And you should not try to use these techniques with
useRef
andif
statements inuseEffect
to make them fire once, or removeStrictMode
, because as you can see in the documentation :If you're still having problems, maybe you're using
useEffect
which, as they say on /learn/synchronizing-with-effects#not-an-effect-initializing-the-application" rel="noreferrer">Not an Effect: Initializing the Application and Not an Effect: Purchase the Product , I recommend you read the article as a whole.