State Management

in UI applications

What is State?

Local state

Global state

  • is a button enabled or disabled
  • is a field editable or read only
  • is a container in a scrolling state
  • is an API endpoint loading
  • does the user have products in the cart
  • is the user logged in

What is state management?

one of the hardest parts of a UI application

in simple terms: it's a combination of design patterns which helps you to synchronise state across all the applications components

Let's break it down

a typical UI application looks like this:

Is there something wrong with this?

Adding some new old concepts

  • observer pattern
  • pub/sub pattern
  • data binding
  • single source of truth
  • immutability
  • unidrectional flow

Observer pattern

implementations: @rxjs/Subject

Pub Sub pattern

implementations: eventemitter2

Data binding

it's a reactivity pattern where an UI component updates based on a piece of state (or data)

global state

local state

const MyComponent = () => {
  const [counter, setCounter] = useState(0);
    
  return(<div>{counter}</div>);
}

Single source of truth

  • the application state is stored in a big object
  • the object is read only and can only be changed via separate functions which are also called actions

Immutability

const state = { users: [] };

// when changing state

state.users = [...state.users, newUser];

libraries in the wild:

immutablejs

why?

for components (observers) to know when to re-render. (oldStateRef !== newStateRef)

Unidirectional flow

Popular implementations

  • redux
  • mobx
Made with Slides.com