the hitchhiker’s guide to redux

Post on 24-Jan-2018

380 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

The Hitchhiker’s Guide to Redux

Sam Hogarth@samhogy

A predictable state container for

JavaScript applications

redux

Web App

LiveStream

Saved Data

User

API

Logging

facebook.github.io/flux/docs/overview

Non-deterministic systems:hard to debug

Change Update Redraw

“Unidrectional Architecture”

UI Events

API Responses

Web Sockets

1) A single source of truth for your application state - as an object tree

2) State is read-only, only actions can change the state

3) Updates to the state are made with pure functions

The Principles of Redux

Store

1) A single source of truth

for your application state -

as an object tree

{authors: {author_1: {

name: “Sam Hogarth”}

},articles: {article_1: {

title: “Redux is AWSM”,content: “I’ll show ya”author: author_11

}}

}createStore(…)

2) State is read-only, only

actions can change the state

getState()dispatch(action)

Action

{type: “SET_TITLE”payload: {article: 1,title: “Redux is Ace”

}}

Store

Action Creator

2) State is read-only, only

actions can change the state

getState()dispatch(action)

function myAction (anArg) {

return {type: { … },payload: { … }

}}

Store

3) Updates to the state are

made with pure functions

update (state, action) => newStatereduce

Reducer function

pure functionA function whose output wholly

depends on its input arguments,

without producing side-effects

var arr = [2, 3, 4];

square(arr)> [4, 9, 16]

square(arr)> [4, 9, 16]> [16, 81, 256]

Math.random()> ?

const initialState = { name: null };

const update = (state = initialState, action) => {

switch(action.type) {

case ‘SET_NAME’:return { …state, name: action.payload };

default:return state;

}};

export default update;

Immutable update

Reducer

Reducer

Reducer

Reducer

Reducer

Reducer

Reducer

Reducer

root

combineReducers({subReducer1, subReducer2, subReducer3

})

function compositionThe result of one function

becomes the input of the next.

The overall result is the result

of the last function.

const square = x => x * x;

cosnt double = x =>x + x;

const squareDbl = x =>square(double(x));

square(3)> 9

double(3)> 6

squareDbl(3)> 36

3) Updates to the state are

made with pure functions

const store = createStore(rootReducer,initialState

);

Render State in the UI

store.subscribe( () => {

const newState = store.getState();

render(newState);

});

Bindings exist for React & Angular2

Change Update Redraw

{type,payload

}

Raise action Subscribe to store, get new state

Reducers

Redux as a Unidirectional Architecture

Keeps reducers simple

Stops unexpected updates

{authors: {

author_1: {name: “Sam Hogarth”

}},articles: {

article_1: {title: “Redux is AWSM”,content: “I’ll show ya”author: “author_1”

},…

},publishedArticles: [

“article_1”]

}

normalization

Q: How can we handle side-effects?

(Network Requests, Impure Functions)

Middleware

A chain of functions that are called before the action reaches the reducers.

Use cases: Logging, Asynchronous Actions, Crash Reporting

Another Middleware

MiddlewareAction

const middleware = applyMiddleware(middleware1,middleware2

);Order is important!

const store = createStore(rootReducer,initialState,middleware

);

Q: How can we handle side-effects?

(Network Requests, Impure Functions)

A: Dispatch something to represent the

side-effect, use middleware to perform the side-effect

thunkA function that wraps an

expression to delay its

execution

function myAsynchronousAction(item) {

return (dispatch, getState) => {

dispatch({type: ‘ITEM_LOADING’

});

return fetch(`/api/items/${item}`).then(result => {

dispatch({type: ‘ITEM_RECEIVED’,payload: result

});

});}

ThunkMiddleware

Action

ActionCreator

type !== function

ThunkMiddleware

Thunk

ActionCreator

type === function

API

LoadingAction

ResolvedAction

Developer Tooling

{type: { … },payload: { … }

}

{type: { … },payload: { … }

}

{type: { … },payload: { … }

}

{type: { … },payload: { … }

}

{type: { … },payload: { … }

}

Can be hot-swapped without affecting stored stateAn audit trail of

state changes

replaceReducer(r)

Conclusion

•Redux is mature, stable, and pretty much done

• Innovations are coming from helper libraries

redux-saga

reselect

The concepts behind Redux will be useful, even if the library falls out of fashion

TIME-Travel Debugging

Immutable architecture

Serializable state

Pure update functions

Alternatives

• Elm – a FP language for the web that inspired Redux

•MobX & CycleJS – Reactive-based state management

•Relay/GraphQL – Query & modify state like a database

Questions?

Sam Hogarth@samhogysamhogy.co.uk

top related