Fetch Data in React With Spinner Only When Necessary
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.