1

UseEffect executes twice when it should execute only once I think. I use useEffect here to fetch some info when the page load, and I need to fetch data only once. I used to do this with the code below, but now I'm facing this problem

import "./App.css";
import axios from "axios";
import { useEffect, useReducer } from "react";

const appInitialState = {
  pageLoading: true,
  adminSignedIn: false,
};
const appStateReducer = (state, action) => {
  if (action.type === "adminSigned") {
    return { ...state, pageLoading: false, adminSignedIn: true };
  } else {
    return { ...state, pageLoading: false, adminSignedIn: false };
  }
};

function App() {
  const [appState, appStateDispatch] = useReducer(
    appStateReducer,
    appInitialState
  );
  useEffect(() => {
    axios.post("http://localhost:8080/admin/v1/isAuthenticated").then((res) => {
      console.log(res.data);
      appStateDispatch({
        type:
          res.data.isAuthenticated === true ? "adminSigned" : "adminNotSigned",
      });
    });
  }, []);

  return (
    <div className="App">
      <h1>App</h1>
    </div>
  );
}

export default App;
Salah a
  • 58
  • 8
  • 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) – gavin May 09 '22 at 19:55
  • 1
    If you're using react18 and strict mode then it's an expected behavior. You can read more about it here: https://pl.reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-strict-mode – m-s7 May 09 '22 at 19:56
  • yes! thank you I needed to remove the React.StrictMode – Salah a May 09 '22 at 19:59
  • 1
    @Salaha You should not remove StrictMode. It gets automatically removed for production builds and is really useful for highlighting potential problems during development. – Eric May 09 '22 at 20:18

0 Answers0