Managing state in an SPA

Managing Single Page Application (SPA) state efficiently and effectively is the second most important decision a software developer has to make when architecting an SPA. Naturally, the most important decision is which framework the application will be structured around, but beyond that, state is what actually brings an application to life, and as such, needs to be carefully crafted.

In the case of SPAs, state is a data structure containing information describing the application at any given point in time. If we had an application consisting of a single toggle, the state might comprise of a description of whether or not that toggle is toggled. This is an example of UI State.

Any state that describes the application’s visual aspects is known as UI state. All other state is generally categorised as Global state. Global state can be data cached from the server, login tokens, or some other data that needs to be persisted/restored between application starts.

A lot of people confuse these two types of state and end up using a single state manager to manage both. For a detailed explanation on why this is very wrong, read through an in-depth analysis here. The long and short of it is that different state managers are built for different things, and like any other software framework, it’s possible to use a state manager for use-cases other than those they’re designed for. In doing so, you won’t reap the rewards of using the framework in the first place.

Recommended ways to architect state in a React application

  • Redux as a global state manager
  • React Contexts to manage the states of hierarchies of UI/presentational components
  • React Component State to manage the states of single UI/presentational components

Conclusion

I see developers overuse Redux time and time again (I’ve been guilty of doing so myself in past projects), when actually React Contexts/Component States are optimised for managing UI states. Omitting UI state from Redux greatly improves its efficiency, cleans up the global state, and improves the encapsulation of presentational components.

As previously mentioned, if you’d like an in-depth analysis of the three state managers mentioned (as well as several others), please see this evaluation I wrote up several weeks ago.

Find more about Tom Szpytman at tomszpytman.com

Like what you read? Give Tom Szpytman a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.