I have an App in reactjs, it should send some data to my back-end Strapi server. So it does, but twice, the sending function works just fine, but the app itself gets rendered twice, thus it sends the data twice.
My code:
import React, { useState, useEffect, useRef } from 'react';
import './App.css';
import { handleData } from './components/Logger';
const App = () => {
const [appHasAlreadyStarted, setappHasAlreadyStarted] = useState(false);
useEffect(() => {
if(!appHasAlreadyStarted){
handleData();
setappHasAlreadyStarted(true);
console.log("send Data to strapi from app")
}
}, []);
return (
<div className="App">
</div>
);
}
export default App;
So I can basically see inside of the console, that the "send Data to strapi from app" ist there (twice), even though i have appHasAlreadyStarted as Guard. What i want ist, that the function handleData() gets called only once, when i start the app.
3
Answers
the effect needs to listen to the variable it should "React" to
note react 18 does a double render in dev mode on purpose. Supposedly it helps catch bugs early. Be sure you are hosting a production ready bundle and not just running a dev server on prod.
Not gonna pretend I know your use case but at a wild guess you likely don’t need the hasappstarted check and are just getting caught up with dev modes double render. handleData could probably just be executed at the top level and a useEffect to process the result
You don’t need any states for that.
Simply run your useEffect with an empty dependency array.
However, your problem might be with StrictMode component. Strict mode renders components twice to catch some errors. It isn’t present in your production build.
You can check that by temporary disabling React Strict mode
When you disable it, your component will be run only once in dev mode.
If you are Development mode, then it is the intended behavior. Components do render twice in strict mode during development.
Try removing <React.StrictMode> from your application. If it is not in Development mode and something else, could you please add more details