I wouldn't remove strict mode as it was enabled in development environment on purpose - to make the app more robust. I had an API call in the component useEffect and I did not want my API to be called twice - even in development - because each API call costs me money. What I ended up doing was to ignore the first call to the API and keep the second call. It worked only this way - trying to keep the first call and ignore the second call did not work and React did not render the DOM that my component returned. In order to do this I used a global variable to count the fetches count:
let globalFetchedCount = 0;
Then in my useEffect I increased the count and called my API:
useEffect(() => { globalFetchedCount++; callTheApi(globalFetchedCount); }, []);
In callTheApi function I checked the value of fetchCount:
const callTheApi= async (fetchCount: Number) => { if (fetchCount === 1 && isDev && isWeb) { console.log('skipping fetch in strict mode fetch count 1'); return; } const response = await doFetch(apiUrl); const data = await response.json(); setMyObject(data.myObject); };
You need to define isDev and isWeb - in my case this was a React Native application and the problem was only in the web version launched by hitting "w" in Expo console.
const isDev = __DEV__; const isWeb = Platform.OS === 'web';
And lastly my component uses MyObject:
export default function MyComponent() { const [myObject, setMyObject] = useState<MyObject[]>([]); ... useEffect(() => { ... }, []} .... // now use myObject return ( <View> ... </View> ); }
StrictModeshould be removed as a last solution. For a more detailed answer see stackoverflow.com/questions/72238175/….