Reputation: 61
StrictMode breaks useState inside of useEffect. Without StrictMode or in build the code works fine.
The setIsLoading should set the state to false in useEffect. setIsLoading(false) "would fix this" but it doesnt explain why the setIsLoading(prevState => !prevState) sets it back to true. Does this only happen because of the StrictModes double render? Or is there a better way to do this?
import { useEffect, useState } from "react";
export default function App() {
const [isLoading, setIsLoading] = useState<boolean>(true);
useEffect(() => {
const getData = async () => {
/*
Some random code would be here
*/
setIsLoading((prevState) => !prevState);
};
getData();
}, []);
return (
<div className="App">
{isLoading ? <div>Loading...</div> : <div>Data has been loaded</div>}
</div>
);
}
Here's a link to a codesandbox if you want to try it out. https://codesandbox.io/p/sandbox/bug-test-39l53k?file=%2Fsrc%2FApp.tsx
Upvotes: 1
Views: 66
Reputation: 1072
Yes, StrictMode is the reason why your isLoading is reset, since the useEffect gets called twice.
What StrictMode does is:
So based on what you want to do, setting isLoading to false could be the correct way to fix your issue.
Upvotes: 1