Fetch Data in React With Spinner Only When Necessary

It seems that on the web there are lots of examples of how to load remote data into a JavaScript React app “Only” after the data has downloaded from the remote server. If you search for keywords like: React; isLoading; Fetch and others, you will find lots of these examples.

I’m surprised that there are not just as many posts that talk about the annoying spinner icon that pops up in the cases that the data loads quickly. That is, if the data comes down the pipe in a couple hundred milliseconds or less, the spinning icon should not be shown at all. Chances our, it will cause an awkward flash that makes you look like a newbie programmer and we certainly don’t want that.

The basic idea is that when the component mounts, we start a simple timer with setInterval. Then, we follow the normal logic for showing a waiting message in react. That is, we have a state variable called isLoading that we only set to true after the rest service has completed it’s download. Where we add an extra wrinkle is we also check to see if the timer has reached some threshold before before showing the waiting message. If it’s not reach the threshold (which is set in the variable showSpinnerIfReturnGreaterThanMs), then we return(null) which basically does not change the DOM at all. In other words, do nothing.

That’s it. Hope this helps. The Gist is below.