Redux

Facebook notification bug

Bug cycle

Complex data flow

Flux

Action

  • Change the state of the app
  • Have the view render differently
  • Has a type
  • Has a payload
  • Describe the entire API - all possible stage changes

Flux

Dispatcher

  • Registry of callbacks
  • Keeps a list of stores it needs to send actions to
  • When an action comes in, pass it to stores
  • Synchronous
  • Possible to set up dependencies
  • Send actions to all registered stores, no matter what action type is

Flux

Store

  • Holds all the state in the app
  • Holds all the state changing logic
  • Store decides whether or not it cares about the action
  • After changing the state, it will emit a change event, notifying the views

Flux

Views

  • Take the state and rendering it out for the user
  • Accepting user input
  • They are not aware of anything in the app
  • Just knows out to output data (HTML)

Flux

Flux did well.

However, Dan Abramov saw an opportunity to improve on Flux

Why?

  • Cutting complexity
  • Provide better developer tools (DX)
    • Hot reloading
    • Time travel debugging

How to improve Flux

  • Hard to hot reload
    • Store contains
      • State change logic
      • Current state itself
  • Solution
    • Separate these two functions
      • One object that holds the state
      • Other object that contains all state change logic

How to improve Flux

  • Hard to time travel debug
    • State is being rewritten with every action
    • Impossible to keep track of old versions
  • Solution
    • When action comes to the store, don't change state
      • Instead, copy the state
      • Make changes to the copy
      • This is achieved by the reducers

Redux

Reducers

Views

----------->

----------->

<-----------

actions

render state

actions

Store

actions

new state

Redux is a predictable state container for JavaScript apps.

Redux principles

  • All state of the app is represented as a single Javascript object
  • State is read-only: you cannot change it
  • If you want change state, you need to dispatch an action
  • Reducer has to be a pure function

Demo

Useful links

  • https://facebook.github.io/flux/
  • https://github.com/reactjs/redux
  • https://egghead.io/series/getting-started-with-redux
  • http://stackoverflow.com/a/32920459
  • https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6#.dd1zeiqjm
  • https://www.youtube.com/watch?v=xsSnOQynTHs
  • http://redux.js.org/docs/basics/UsageWithReact.html

Thanks!

Redux

By Diogo Lucas

Redux

  • 438
Loading comments...

More from Diogo Lucas