React 18, useEffect is getting called two times

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;

Sandbox

>Solution :

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, watch this YouTube Short Video. For now, you can avoid it with a boolean ref, 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]);
console.log("rendered");
  return (
    <div>
      <h1> Counter </h1>
      <div> {count} </div>
      <button onClick={() => setCount( count + 1 )}> click to increase </button>
    </div>
  );
};

export default Counter;

Leave a Reply