Reputation: 3730
I am trying to display a loader till the page finishes rendering and for that I used this code:
export default function App() {
const [isLoading, setIsLoading] = React.useState(true);
const handleLoading = () => {
setIsLoading(false);
};
useEffect(() => {
window.addEventListener('load', handleLoading);
return () => window.removeEventListener('load', handleLoading);
}, []);
return (
<div>
{isLoading ? (
<Load />
) : (
<div className="app">
<Topbar />
<div className="parts">
<Intro />
<About />
<Projects />
<Contact />
</div>
</div>
)}
</div>
);
}
This works fine on desktop devices except in incognito mode and in mobile devices.
It shows the loader forever and when I press the refresh button twice only then will the page appear.
I tested the site on gtmetrix
and I got this error: Lighthouse Error: The page did not paint any content
.
How do I solve this?
Upvotes: 0
Views: 164
Reputation: 323
useEffect will get called when your state has changed, right?
then when do you think your useEffect will be called?
the component is created, the loading state is set to true, and everything is working good, why would your component calls your useEffect when the state is not even changing?
i have two suggestions:
remove your 'load' event listener and add it to your main function code, this way the event listener will be initiated. then when the page loads, it will set your state into false, thus your useEffect will be called, and it removes the event listener.
is to use class based components with lifecycle hooks that are designed for what you are trying to do.
Upvotes: 1
Reputation: 3549
I'm not sure that eventListener works fine in your case but if I were you I would simply setIsLoading(false) in useEffect and if you want it to stop before Component mounts you can do it in this way :
export default function App() {
const [isLoading, setIsLoading] = React.useState(true);
const [mounted,setMounted] = React.useState(false);
if(!mounted) setIsLoading(false)
useEffect(() => {
setMounted(true)
}, []);
return (
<div>
{isLoading ? (
<Load />
) : (
<div className="app">
<Topbar />
<div className="parts">
<Intro />
<About />
<Projects />
<Contact />
</div>
</div>
)}
</div>
);
}
hope it was helpful ;)
Upvotes: 1