skip to Main Content

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;

2

Answers


  1. 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.

    Login or Signup to reply.
  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();
      };
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search