Redux Crash Course

@jumbosushi

WHY

WHAT

HOW

WHAT

HOW

Why use Redux?

What problem does Redux solve?

STATE

@christianalfoni

A data you use to populate a template

Model

Model

Model

View

View

View

STATE

Flux

Elm

Elm

(action, state) => state

WHY

WHAT

WHAT

HOW

WHY

(state) => view

Action

Reducers

dispatch

oldState

Store

Single source of truth

State is read-only

Changes are made with pure functions

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)

Following examples are inspired from http://mae.chab.in/archives/2885

Store Code

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

const store = createStore(reducer, initialState);

Using Store

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


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

Reducer Code

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

That's it!

CSS-Tricks

 https://css-tricks.com/learning-react-redux/

Wait wut

Isn't it back to MVC?

It's all about the view

WHAT

WHAT

HOW

WHY

HOW

Example

Example

Smart vs Dumb 

Smart: Describe how things work
- Provide no DOM markup or styles
- Provide application data, do data fetching
- Call Flux actions
- Named *Container by convention

Dumb: Describe how things look
- Have no app dependencies
- Receive only props, providing data and callbacks
- Rarely have own state, when they do, it’s just UI state
- Named anything that’s a UI noun

From https://jaketrent.com/post/smart-dumb-components-react/

Smart vs Dumb 

From https://jaketrent.com/post/smart-dumb-components-react/

Smart vs Dumb 

From https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

Better separation of concerns

Better reusability

Presentational components

become app’s “palette”

"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

React & Redux can be used in many ways

SHOW CASE

React Router

React Visualized

https://bvaughn.github.io/react-virtualized/#/components/Collection

https://bvaughn.github.io/react-virtualized/#/components/Collection

React Storybook

http://airbnb.io/react-dates

Thanks!

@jumbosushi

Redux Crash Course @ OttawaJS

By Atsushi Yamamoto

Redux Crash Course @ OttawaJS

  • 376
Loading comments...

More from Atsushi Yamamoto