Redux 101

http://christianhall.me/redux-101/

Christian Hall

Lead Developer @ Good

Redux 101

  • Background
  • Principles
  • Basics
  • Example
  • Reasoning
  • Extras
  • Resources

Disclaimer

Do I need Redux to write good React apps?

Should I switch from (insert framework) to React + Redux right now?

Will my app/startup/life fail if I'm not using Redux?

NO

Use what works for you. If you like some of the ideas behind Redux, use it or find a way to use the ideas with your stack.

Background

MVC

Flux

Flux

Motivation

  • Increasing front end complexity
  • Poor state management
  • Mutations and asynchronicity

Inspiration

  • Flux ((state, action) => state)
  • Elm (Functional language based on model-view-update)
  • Immutable

Principles

Single source of truth

State is read only

Changes are made with pure functions

Redux

Actions

Plain JavaScript Objects

Only source of information for the store (via dispatch)

Must have a type

Action creators are just functions that return actions

Actions


{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}
						

Reducers

Specifiy how app's state changes in response to an action

(previousState, action) => newState

Must be pure functions

Can be composed to manage different parts of state tree

Reducers


function todoApp(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return Object.assign({}, state, {
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      })
    default:
      return state
  }
}
						

Store

Holds application state

Allows access to state via getState()

Allows state to be updated via dispatch(action)

Handles low level listeners

Data flow

  1. An action is dispatched
  2. The store calls the reducer function(s)
  3. The root reducer combines the output of all reducers
  4. The store saves the complete state tree from the root reducer

Usage with React

Requires react-redux for bindings

Component hierarchy should match state tree design

Container and presentational components

Example

Reasoning

Pros

  • Documentation
  • Ecosystem + Ergonomics
  • Community + Dan Abramov
  • Just JavaScript
  • Easy Onboarding
  • Essentially Finished

Cons

  • New and Unproven
  • Paradigm Shift
  • JavaScript Fatigue
  • Boilerplate

Extras

  • Middleware
  • Async Operations
  • Immutable
  • Normalizr
  • Routing
  • Webpack
  • Other Frameworks

Resources

fin

Sources

  1. http://staltz.com/unidirectional-user-interface-architectures.html
  2. https://medium.com/brigade-engineering/what-is-the-flux-application-architecture-b57ebca85b9e#.8aiad2fmc