Issue
I'm building an Ionic 7, React 18 application and having some trouble understanding a basic useEffect principle. I have this App.tsx file
setupIonicReact();
const App: React.FC = () => {
useEffect(() => {
console.log("Loading user profile info in app..." + new Date().getUTCMilliseconds());
UserService.getProfile()
.then((user) => {
console.log("User: " + JSON.stringify(user));
})
.catch((error) => {
console.error("Error fetching profile:", error);
});
}, []);
return (
<IonApp>
<IonReactRouter>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonButton>
<IonIcon icon={logoReact} />
</IonButton>
</IonButtons>
<IonTitle>LOL Greetings</IonTitle>
<IonButtons slot="end">
<IonButton>
<IonIcon icon={search} />
</IonButton>
<IonButton>
<IonIcon icon={personCircle} />
</IonButton>
</IonButtons>
</IonToolbar>
<IonToolbar>
<CategorySelectComponent />
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding" scroll-y>
Test
</IonContent>
</IonReactRouter>
</IonApp>
);
};
export default App;
This is called from my mainn.tsx file
const container = document.getElementById("root");
const root = createRoot(container!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
THe problem is I'm noticing the "useEffect" is getting called twice (I can see two calls to my UserProfile.getProfile" call. How do I ensure that it is only called once? I thought that passing an empty dependency array ensures the useEffect only executes once, but I guess I'm wrong about that.
Solution
Don't worry, since you have used <StrictMode>
, your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup. In your production build, your effects will be run only once.
See https://react.dev/reference/react/StrictMode.
Answered By - ray
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.