Front-End State Management

What is a "state"?

A state is a representation of a system in a given time

What's stored in the state?

  • Component: Is the dialog open? Is the form valid?
  • Network: Is the user logged in?
  • Communication: Are we in the process of fetching stuff from the server?
  • Navigation: Where are we in the application? Which page are we looking at?

State management

The problem

App

Component 4

Component 5

Component 6

Component 1

Component 2

Component 3

...we have to keep it crisp, disentangled, and simple if we refuse to be crushed by the complexities of our own making...

 

Edsger W. Dijkstra

How to fix this problem?

"Single source of truth"

State

Component 4

Component 5

Component 6

Component 2

Component 3

Component 1

App

Advantages

  • State is immutable and predictable
  • Contains the least amount of data possible, the rest can be derived
  • Decouples components
  • Improve maintainability and scalability
  • Easier to test and debug
  • Persistent

Drawbacks

  • HIgher learning curve
  • More boilerplate code
  • More complexity

How to implement State Management?

Principles

  • Represent all state data uniquely as variables/properties
  • Represent all derived data in your application as functions/methods
  • Explicitly define dependencies in your data and avoid circular dependencies
  • When state data changes, recalculate derived data in dependency order (topological evaluation)
  • Never change state while deriving, never derive while changing state
  • Prefer abstractions for the native DOM over templates and DSLs
  • Prefer state that is as localised in scope as possible.

Redux, XState, MobX, NgRx, VueX, Recoil...

The Flux architecture

View

Action

Dispatcher

Store

Action

Made with Slides.com