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
Remove <React.StrictMode> from index.js This code will be
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.
initFirebase
function is running twice because you are using React 18 andStrictMode
. React 18 introduced a change in the default behavior ofuseEffect
in development mode when usingStrictMode
.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.comTo avoid running twice, you can use cleanup function in
useEffect
hook.For example: