0

I am so confused here with React useEffect Hooks with setTimeout. I have exactly the same code as w3school https://www.w3schools.com/react/showreact.asp?filename=demo2_react_useeffect_settimeout2

but my code is rendering "I've rendered 2 times" instead of "I've rendered 1 times". And I have tried it in many code editors, and mine always shows 2..

My: enter image description here

And the only way I can get it to render 1 is refactoring to this instead

useEffect(() => {
     setTimeout(() => {
     setCount(count + 1);
   }, 1000);
 }, []); 

Could someone please explain to me why? Thanks for your help!

I am expecting my code to render the same result as w3school example.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

0

Take a look at this similar question. To summarize, this is an intended feature of React Strict Mode. If you remove any <StrictMode> tags from your code or build your React app, the problem should go away.

Also, I suggest using count callback variable: setCount((count) => count + 1)) instead. It'll insure your state increments properly from the previous state because React will not immediately update the count state variable. This probably won't affect simple state change, but if your state updates often, it'll prevent your state from losing track of the previous state value.

Nabeel Ahmed
  • 146
  • 1
  • 4
  • Thank you and that solved the issue! Now I'm curious should we still use strict mode? Additionally to setCount((count) => count + 1)) , I have seen a lot of people use that, including myself.. but they give example on official React doc https://reactjs.org/docs/hooks-state.html as function Example() { const [count, setCount] = useState(0); return (

    You clicked {count} times

    ); } The more i dig into the more I get confused about the best practice.
    – user17591453 Jan 27 '23 at 21:11
  • If you're just making a React project to learn about the library, Strict Mode isn't going to be of any great use to you. It's mainly used during development where it provides more detailed errors and warnings. Next, I'd say the better practice is to use `setCount((count) => count + 1)`. It won't make a huge difference with smaller applications, but as your state complexity grows, it'll make sure your state is properly updated. At the end of the day, it's a net positive, as you're not really losing anything from using this convection and it helps fix state-related bugs. – Nabeel Ahmed Jan 28 '23 at 03:28