1

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!

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
Sarah
  • 292
  • 1
  • 10
  • 1
    What do you mean by *useEffect is not called*? – Konrad Sep 22 '22 at 20:51
  • Does this answer your question? [React Hooks: useEffect() is called twice even if an empty array is used as an argument](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) – Konrad Sep 22 '22 at 20:52
  • 4
    If you're using react 18 and strict mode, react will mount each component twice initially (only in development). It's covered in their docs. – super Sep 22 '22 at 20:52
  • 1
    An `useEffect` should always run one time on mount and then every time the component re-renders and a variable in the dependency array changes. Now why it's running twice on mount? See [useEffect is running twice on mount in React](https://stackoverflow.com/questions/72238175/useeffect-is-running-twice-on-mount-in-react) for a detailed answer. – Youssouf Oumar Sep 23 '22 at 17:30

1 Answers1

0

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

rantao
  • 1,621
  • 4
  • 14
  • 34