How Loading States in React Help Users *and* Developers

Loading notification

Working with states in React can be abstract and difficult to grasp at first — so it’s a variable? No. But it holds data and that can be reassigned? Well, yes. After working with it more and seeing how flexible state can be, you’ll come to think of state as your best friend. However, states have their limitations and understanding how to account for your initial state values can help users and yourself in the long run.

Recently, I was working on some simple code that would render information to a details page when the page first loaded. This needed both useEffect and useState to pull the information and hold it in state respectively, no big deal.

I imported useEffect and useState, set my initial state to null knowing I’d be populating it soon after loading, and used a fetch request inside of useEffect to pull information from my database and update state with the new information. After setting the new state, I wrote a line deconstructing state to access the variables I needed. I went about my merry way, checked my rendering, and saw a sight that is likely familiar to you if you’ve just started working in React:

I checked my fetch request — it was working fine. I checked state after running the fetch — all good. So what was React’s problem??

As some of you might have already guessed, I was asking a little too much of React and state. As you might remember, I set my initial state as null in anticipation of populating it as soon as the page loaded. An understandable assumption, but React can’t operate on a null state for the split second before our fetch request has been rendered. Luckily for us, there’s an easy workaround that not only helps you, but can also help you users — I’m calling it a load state.

If we initiate a new load state for the page that accounts for whether or not the page is loaded (in this case, isLoaded), React is mollified knowing that you are accounting for any initial null states, and React now has something to display while your fetch request is running. This fix also benefits your user — if something goes wrong while your page is rendering, a user is much more likely to understand this if they see a dreaded “Loading…” message while waiting.

While adding a feature like a load state or load message could, at first glance, seem like an extra feature that is nice to have but ultimately unnecessary, consider your initial states and what React will (and will not) be able to do with them.

Software Engineering student at Flatiron School. Based in Brooklyn.