Redux in Action

Part One: Core Concepts

Redux | Core Concepts

  • Store
  • Action
  • Reducer

store

action

reducer

store

reducer

Redux

state

action

UI

DOM Event 

Network 

……

Redux | Core Concepts

Redux | Core Concepts

Redux | Three Principles

  • Single source of truth
  • State is read-only
  • Changes are made with pure functions

Redux's primary goal is to make state mutations predictable 

by imposing restrictions on how and when updates can happen.

Redux | Three Principles

  • Single source of truth

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

 Tips

 

 

 

 

  • You don't have to put everything into Redux.
  • Only put plain serializable objects, arrays, and primitives into your store.
  • Each entity should be stored once.

Redux | Three Principles

  • State is read-only

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

 Tips

 

 

 

 

  • Actions that reach the store must be plain objects, and actions must have a type field that is not undefined.

Redux | Three Principles

  • Changes are made with pure functions

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

 Tips

 

 

 

  • The single root reducer function can itself be made up of many smaller reducer functions.
  • Predictable
  • Hot reloadable
  • Time travel
  • Easy to test
  • Doesn't care how you store your data
  • The API surface area is minimal
  • Provides extension points

Redux | Philosophy & Design Goals

  • createStore(reducer, [preloadedState], [enhancer])
  • applyMiddleware(...middleware)

Redux | Enhancer & Middleware

Redux | Enhancer

 redux/createStore.js

createStore

const enhancers = [enhancer1, enhancer2, enhancer3];

const enhancer = compose(...enhancers);

 Enhanced createStore

enhancer3

enhancer2

enhancer1

reducer,preloadedState

Redux | Middleware

 redux/createStore.js

dispatch

const middlewares = [middleware1, middleware2, middleware3];

applyMiddleware(...middlewares);

 Enhanced store.dispatch

middleware3

middleware2

middleware1

action

Redux | Review

store

reducer

Redux

state

action

UI

DOM Event 

Network 

……

React-Redux

React

React-Redux | API

  • connect([mapStateToProps], [mapDispatchToProps])
    • Handles the process of subscribing to the store
    • Extracts the pieces of state the wrapped component needs
    • Ensures the wrapped component only re-renders when needed
    • Shields the wrapped component from needing to know that the store exists
  • <Provider store>
    • Pass the store to connected components by context

React-Redux | API

store

Provider

Root

Component

Sub

Component

Sub

Component

Wrapper

Component

store (by context)

props by

mapStateToProps &

mapDispatchToProps

 

React-Redux | Presentational and Container

Redux in Action - Core Concepts

By yiliang_wang

Redux in Action - Core Concepts

  • 120