React: console log is printed twice before useEffect is invoked

Viewed 46

I am learning react and in particular I am studying useEffect; i am not able to understand why as soon as i run the code the console log is printed twice even if useEffect is not called.

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("test");
  }, [count]);
  return (
    
    <>
      <button onClick={() => setCount(count + 1)}>+</button>
      <p>Add: {count}</p>
    </>
  );
}

Thanks to those who will help me!

2 Answers

Using React 18 in strict mode will cause your components to render twice in development.

This is expected and shouldn’t break your code.

This development-only behavior helps you keep components pure. React uses the result of one of the calls, and ignores the result of the other call. As long as your component and calculation functions are pure, this shouldn’t affect your logic. However, if they are accidentally impure, this helps you notice the mistakes and fix it.

Reference: React Docs

The UseEffect is run automatically every time that the component is rendered, probably when the page is first rendered and then again when the component is rendered. Maybe you doesn't need UseEffect. But you can put it inside another function, making it possible to control.

Related