fordat
fordat

Reputation: 628

React render after effects from loading spinner

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:

  1. Putting my setIsFinishedLoading(true) in a setTimeout(),
  2. 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.

Upvotes: 0

Views: 150

Answers (1)

YinPeng.Wei
YinPeng.Wei

Reputation: 598

Because of some of your Dom need the data whose got in async HTTP apiGet. They will appear later than other Dom whose not need api.

If you want to show both of them at the same time ,you may need to promote your Loading and state to a parent's component to control all Dom's display while data is got from apiGet .

Upvotes: 0

Related Questions