I have a React application with a loading spinner that goes away when an API call finishes. I have the loading spinner set up to render in my index file like this:
if (isFinishedLoading === false) {
return (
<LoadingSpinner/>
);
}
return (
{rest of code}
)
Where isFinishedLoading
is false as set by useState. I call the needed API like this in useEffect:
useEffect(() => {
apiGET()
}, [])
and I call setIsFinishedLoading(true)
inside of apiGET()
.
However, there is always a split second where the page is not fully rendered, it looks like some divs appear before others and the site flickers a little bit, it doesn’t look like a fully rendered site.
My question is: is this just a fact of using React that it will take a half second for the page to fully render? Or am I implementing my loading spinner in the wrong way?
I’ve tried a few things:
- Putting my
setIsFinishedLoading(true)
in a setTimeout(), - Adding an additional loading flag to wait until all images are loaded like this: React: Show loading spinner while images load
Ideally, I’d be able to call something like img “onLoad” for divs, but that sounds a lot like useEffect() anyway. For what it’s worth, the application is in Gatsby.