1

I'm initializing firebase when the react app runs. Since I'm calling initFirebase on component mount, it should be called only once. But in my console, I see "Initialized firebase app" twice. Why is the function runnning twice?

The relevant code:

function App() {
  const [FBApp, setFBApp] = useState(null);

  useEffect(() => {
    let app = initFirebase();
    setFBApp(app);  
  }, [])

  const router = createBrowserRouter([{
    path: "/",
    element: <HomePage />
  },
  {
    path: "/admin",
    element: <AdminPage />
  }
])

  return (
    <FirebaseAppContext.Provider value={{FBApp, setFBApp}}>
      <RouterProvider router={router} />
    </FirebaseAppContext.Provider>
  )
}


//initFirebase.js
import { initializeApp } from "firebase/app";

const initFirebase = () => {
  const firebaseConfig = {
    apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
    authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
    projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
    storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
    appId: import.meta.env.VITE_FIREBASE_APP_ID,
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  console.log("Initialized firebase app", app);
  return app;
};

export default initFirebase;

U. Watt
  • 533
  • 1
  • 5
  • 27
  • 1
    in dev useEffect always run twice - https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar – Sonu Sindhu Jul 10 '23 at 07:02
  • Ah, it seems it's due to the strict mode, which is enabled in my app. Thanks – U. Watt Jul 10 '23 at 07:05

2 Answers2

2

initFirebase function is running twice because you are using React 18 and StrictMode. React 18 introduced a change in the default behavior of useEffect in development mode when using StrictMode. StrictMode is a tool that helps you find potential problems in your app by activating additional checks and warnings. One of these checks is to render the component twice on mount and unmount, which causes useEffect to run twice as well. This is done to detect any side effects that are not properly cleaned up or depend on the render order. To learn more, see Why does useEffect run two times? - flaviocopes.com

To avoid running twice, you can use cleanup function in useEffect hook.

For example:

useEffect(() => {
  let app = initFirebase();
  setFBApp(app);
  return () => {
    app.delete();
  };
}, []);
Pluto
  • 4,177
  • 1
  • 3
  • 25
0

Remove <React.StrictMode> from index.js This code will be

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

React StrictMode renders components twice.

one more reason can be this code is triggering re-render in parent component that is making it run it twice.

gilf0yle
  • 1,092
  • 3
  • 9