0

We switched to React 18 from react 17. Strangely all the API code that is running during component mount in useEffect has started executing twice. When we applied console we found that it look like component mounting, then unmount and then remounting. Let me share a code snippet that illustrate this behaviour:

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [apiCalled, setApiCalled] = useState(0);
  const callApi = () => {
    setApiCalled((prev) => prev + 1);
  };
  useEffect(() => {
    // Mount component
    callApi();
  }, []);
  return <div className="App">Api Called: {apiCalled}</div>;
}

Here output is: Api Called: 2 While expected output is: Api Called: 1

This is working alright in version 17. Please help me know resolution of this problem.

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
  • 2
    This is normal. It's because of [React Strict Mode](https://reactjs.org/docs/strict-mode.html) which mounts-unmounts-remounts components to detect potential issues within the React app. – ivanatias Oct 31 '22 at 08:03
  • I suggest you to always read the release notes when upgrading the major version of a library you're using, so you can know what changed. – Guillaume Brunerie Oct 31 '22 at 08:05

0 Answers0