Redux in a Row

David Khourshid

Who the duck is David Khourshid?

This guy

Your data flow sucks.

How you think your state is organized

How your state is really organized

Culprits:

  • Mutable state
  • Two-way data binding
  • Key-value observables
  • You

Symptoms:

  • Race conditions
  • Indigestion
  • Difficult debugging
  • Fragile unit tests
  • You getting fired

How do we unduck our state?

Pure Functions.

function add(a, b) {
  return a + b;
}

add(1, 2); // 3

Given the same input, always returns the same output.

function isAngular2ReleasedYet() {
  return false;
}

isAngular2ReleasedYet(); // false

Stateless.

Goes hand-in-hand with pure functions.

Stateful: "How many goats do you have right now?"

Stateless: "If you had 3 goats and I gave you a goat because I am a generous goat lover, how many goats do you have?"

Single state.

Don't be like this guy.

Do one thing at a time.

Single state.

Single state.

Actions

Reducer

(   ,   ) 

Pure function

Immutable state

New state

New State

New State

Action creators

(...) => { type, ... }

function addDuck() {
  return { type: 'ADD_DUCK' }
}

function removeDuck() {
  return { type: 'REMOVE_DUCK' }
}

Reducer

(state, action) => state'



function duckReducer(state, action) {
  switch (action.type) {
    case 'ADD_DUCK':
      return {
        ...state,
        count: state.count + 1
      }
    case 'REMOVE_DUCK':
      return {
        ...state,
        count: state.count - 1
      }
    default:
      return state;
  }
}

Store

(reducer, initialState) => store

const INITIAL_STATE = { count: 0 };

let store = createStore(duckReducer, INITIAL_STATE);



store.dispatch(addDuck());

store.subscribe(() => {
  console.log(store.getState());
})

store.dispatch()

store.subscribe()

store.getState()

Combine Reducers

{r, r, r, r...} => r

let store = combineReducers({
  duck: duckReducer,
  goat: goatReducer
})
compose(f, g)(x) == f(g(x))

Combine Reducers

Instead of:

{
  ducks: 3
}

You have goats:

{
  duck: {
    ducks: 3
  },
  goat: {
    goats: 4
  }
}

Pub/Sub

  1. Publish: you order a sub
  2. Subscribe: when an order is received, a delicious sub is created

Architecture

Live coding

unless I ran out of time.

NO REACT!