Atsushi Yamamoto
@jumbosushi

Atsushi Yamamoto
@jumbosushi

WHY

WHAT

HOW

WHAT

HOW

Why use Redux?

What problem does Redux solve?

STATE

@christianalfoni

A data you use to populate a template

STATE

Model

Model

Model

View

View

View

STATE

Flux

Flux

Elm

Elm

 “model view update” architecture

(action, state) => state

Immutable

WHY

WHAT

WHAT

HOW

WHY

(state) => view

Action

Reducers

dispatch

oldState

Store

Action

{
  type: "EXAMPLE_ACTION",
  payload: {}
}

Reducer

const initialState = {}

function reducer(state = initialState, action) {
  return state
}

(state) => view

Action

Reducers

dispatch

oldState

Store

(action, state) => view

Single source of truth

"The state of your whole application is stored in an object tree within a single store."

State is read-only

"The only way to change the state is to emit an action, an object describing what happened."

Changes are made with pure functions

"To specify how the state tree is transformed by actions, you write pure reducers."

Changes are made with pure functions

The output of a pure functions depends only on inputs

Has no side-effects

Pure functions have no state

Changes are made with pure functions

Reducers are pure functions

Data logic is 100% separated from view logic

ActionA

ActionC

ActionB

Kept in Store

How is it different from React?

Store ≈ this.state 

Actions & Reducers ≈ this.setState 

always render with from store

≈ re-render with this.setState 

It's about giving the application a single state (store)

Lifting the state

Lifting the state

Eventually, React will start doing more than it should.  

The Role of the Store

- Hold the state

- Expose state by store.getState()

- Update state by store.dispatch(action)

- Add a listener with store.subscribe(listener)

Store

// Create initial state
const initialState = {
  value: null,
};

const store = createStore(reducer, initialState);

// Get current snapshot
store.getState()

Using Store

// Initiate action
store.dispatch({type: 'SOME_ACTION', value: 'EX_VALUE'});


// Called once there is change in state
store.subscribe(() => {
    // Do something
});

Reducer

// Reducer
testReducer(state, action) => {
  switch (action.type) {
    case SOME_ACTION:
      return Object.assign({}, state, {
        value: action.value,
      });
    default:
      return state;
  }
}

That's it!

Wait wut

Isn't it back to MVC?

It's all about the view

M

V

C

V

M

V

C

WHAT

WHAT

HOW

WHY

HOW

Example

Example

"I would like to amend this: don't use Redux until you have problems with vanilla React."

Dan Abromov

http://redux.js.org/docs/faq/General.html

Brevity

Predictability

Vuex

Mobx

?

Thanks!

Atsushi Yamamoto

@jumbosushi

State Management with Redux @ DevTeach Montreal

By Atsushi Yamamoto

State Management with Redux @ DevTeach Montreal

  • 1,556