SlideShare a Scribd company logo
1 of 41
Download to read offline
The Road To Redux
The React + Redux + Immutable + ES6 Combo
Notes From My Crash Course In Redux So Far...
By Jeff Sanchez, consultant @ Cielo Concepts
Why React?
● Fast Rendering Updates (via the much touted “virtual DOM” and
associated efficient diff when deciding what to re-render)
● Relatively Easy to Understand (especially in more complex examples)
● Large + Growing Enthusiasm / support from tech giant + community
● Scales Well (especially with the help of additional libraries)
● Easy to Debug (in some sense, there’s not much to go wrong in any given
component)
● Flexible - less of a commitment (not really a framework) - use as little or as
much of it as you’d like
● Helpful JSX HTML-ish Language
■ (optional, but you’ll probably want it)
Feel the React Momentum! (from Google Trends)
JavaScript Frameworks/Libraries With Similar Goals, Or
Otherwise Mentioned In The Same Conversation As React
● Angular / MEAN stack
● Ember
● Backbone
● Ext JS / Sencha
● Polymer
● Meteor / Blaze
● Knockout
...And many more lesser known ones. Of the ones I’ve tried,
React has been the easiest (at least, for rapid prototyping).
Also appears to have more momentum than these do.
The Oft Done Angular Comparison
Angular
● Two-way data binding
● Fairly heavyweight framework
● directives, controllers, services
● Can be hard to reason about the flow in
some more complex examples
● Inject data via scopes
● More intuitive looping constructs
(arguably)
● Backed heavily by Google
● Large established ecosystem
React
● Uni-directional data flow (Flux pattern)
● Easy composition / nesting of
components
● High performance via virtual DOM
● JSX syntax (optional)
● Inject data via props
● Backed heavily by Facebook
● Context switching in JSX land can be
jarring
● Smaller ecosystem, though growing fast
Our 10,000’ View is…
● React, for easy componentization / organization of UI elements
● ES6 (ECMAScript 6), for more elegant, easier to read JavaScript code
● Redux, for predictable, manageable application state
● Node.js for many supporting modules for JavaScript SPAs
● Immutable, to help enforce the “Redux Way” (and thus reduce bugs)
● Webpack + Babel, for bundling, hot reloading, JavaScript ES6+ language
features, etc.
● Pattern Lab, for our ‘living styleguide’ / atomic design approach
Steps For Developing A React App
From the Facebook React docs, here’s one suggested approach:
1. Initially, start with a mockup of what a particular page should look like
2. Break the UI into a component hierarchy
3. Build a static version in React (i.e. don’t use state at all yet)
4. Identify the minimal, complete version of the state of the UI
5. Determine where the state should live, at a component level
6. Add inverse data flow as needed (data flowing from components deep in the
hierarchy to ones closer to the top)
The React Approach, Cont.
Create components that can be easily composed into larger components,
ultimately making up views.
Components can maintain their own state, and/or can instead have it driven
via “props” from parent components
Flexible, less opinionated library + optional expanding ecosystem === use as
little or as much of the React world as you’d like.
Unidirectional flow makes debugging / reasoning about app behavior easier -
it’s one of the main differentiators between React and Angular.
Some React Basics
● Component properties are passed from parent component to child, read-only
from child’s point of view
● Component can maintain internal state via ‘state’ property
● render method outputs React DOM (virtual DOM) elements to be transformed
into actual DOM elements by React
● Lifecycle methods provided before/after rendering for components
● Easily inline styles with style objects
● Components can contained nested components, and reference other
components via refs
● JSX syntax makes component rendering easier to follow
Many Useful Node.js Modules in React ecosystem
Thankfully, there are well tested React/Redux components and associated Node
modules (check out npmjs.com, react.rocks, and react-components.com) for:
● Grids (react-datagrid)
● Tabs (react-tabs)
● Forms (redux-forms)
● Modals (react-modal)
● Actions (redux-actions)
● Logging (redux-logging)
● Routing (redux-simple-router)
● Asynchronous requests (redux-promise, redux-thunk)
● And many more!
A Bit About React’s JSX language...
JSX is a JavaScript extension that looks similar to XML. It’s optional in React, but
is encouraged and used quite a lot. Why? JSX is an easier, more readable syntax
for laying out nested component UI.
Typically, you’ll find it in the render method for a React component, when returning
what to render. For example:
render () {
// JSX - note the JS expression referencing prop values:
return <div>Hello {this.props.name}!</div>;
}
ES6 - The JavaScript We’ve Been Looking For
Coming from a Java background myself, some of these changes are quite
comforting:
● Class syntax
● Module import
● Arrow functions (similar to lambda expressions in Java 8)
● Destructuring
● Rest Spread operator
● Improved iterators
● Template strings
ES6 Highlights
Arrow functions are particularly useful, succinct language additions:
E.g.: ES5 “old way” (var and function keywords):
var nums = [1, 2, 3, 4, 5, 6];
var squares = nums.map(function (x) { x * x));
Rewritten function with ES6 arrow functions:
let squares = nums(x => x * x);
ES6 + React Usage
ES6 classes + constructors + module imports work nicely with React:
import React from ‘react’;
export default class Book extends React.Component {
constructor(props) {
// possibly set up state here, bind functions, etc.
}
render () {
return (
<div className=”book”>
<BookSummary id={this.props.id} />
<AuthorBio name={this.props.author} />
</div>
);
}
}
More ES6 Slickness
Destructuring examples, both for arrays and objects:
let arr = [1, 2, 3, 4];
let [first, ,third] = arr; // first === 1, third === 3
let person = {firstName: “Mike”, lastName: “Smith”, age: 30};
const {firstName, age} = person; // firstName === “Mike”, age === 30
Pretty common to see this pattern at the top of render() methods in React/Redux components:
render () {
const {dispatch, someProp, anotherProp} = this.props;
}
Motivations for Flux (which is…?)
We should address Flux a bit before talking about Redux:
Flux addresses component state management for more complex React
applications. Technically, it’s just a pattern of uni-directional data flow
development embraced by React. (There are various implementations of Flux.)
Improves code management moving the storage outside of the
component.
More Flux Overview
State is moved to stores, components dispatch actions to the stores via the
dispatcher, and their rendering is (mostly) driven by props.
Controller-views (typically, top level components) receive change events emitted
by stores and update their state and their children’s state appropriately.
The Flux flow looks like this:
ACTION DISPATCHER STORE
ACTION
VIEW
Flux Implementations
● Alt (pretty popular - see SurviveJS leanpub book for some good examples)
● Flummox (apparently nearing end of life)
● Reflux
● Facebook’s Flux
● Fluxxor
● … Some more obscure ones with “Back to the Future”-related names...
● Redux (Not exactly Flux, as we’ll see...)
More complete Flux implementation list with some demos: https://github.
com/voronianski/flux-comparison
Redux - Not Exactly Flux
Motivation: How best can we make state mutations predictable in SPAs (Single
Page Applications)? Can we support hot reloading / “time travel” debugging /
middleware better?
Redux answer: impose restrictions on how / when we can make these state
mutations. Their 3 principles:
● Single source of truth
● State is read-only
● Pure functions transform state + action into new state
Redux Benefits
● Hot reloading (don’t lose app state after a code change in a running app
instance)
● Time travel debugging (revert to an older application state just by replacing
the current state with an older application state snapshot)
● Centralized application state tree (“single source of truth”) - easy to drill down
into when debugging. It’s just a big tree data structure (of maps, lists, sets).
● No need to manage multiple stores like in Flux implementations.
● Minimal size (2K!) and simple API.
Redux Concepts
● Actions - created and dispatched to the reducers, which typically produce a
new app state
● Reducers - take state + action, and produce the next state
● Store - place where entire application state is stored
● Data Flow - unidirectional (view -> action -> store -> view)
● Thunks for Async actions (cannot have side effects in reducer pure functions)
● Immutability (correctness and performance reasons)
● Middleware (e.g. logging)
● No dispatcher (unlike Flux)
Immutable and Redux
Problem: how can we prevent inadvertent state mutations, which could cause
subtle bugs in the Redux world?
Answer: enforce immutability by using Immutable.js or similar library
Immutable provides data structures such as Sets, Lists, Maps that cannot be
mutated. Instead, data structure methods that look like mutators actually return
new instances of the data structure they operate on (e.g. set.add(‘something’)
returns a new set with ‘something’ added to the original set).
Immutable Benefits
● Performance boosts in part due to comparison via === (as opposed to deep
comparison) when React needs to determine what should be re-rendered.
● Enforces the Redux state immutability concept, thus reducing bugs
● Pretty powerful data structure library for manipulating Sets, Lists, Maps, etc.
● Well tested / supported
● Painlessly convert to/from ordinary JS objects (with toJS()/fromJS())
Redux Utilities / Related Modules
● redux-logger - easy to use logger middleware
● redux-actions - help organize your redux actions
● redux-thunk - asynchronous support (e.g. for AJAX requests)
● redux-router / redux-simple-router - routing support (map paths to
components)
● redux-promise - promise support
● redux-devtools - debugging tools (easily navigate current state of redux app
state)
● redux-form - nice form support, particularly around validation
Useful Redux Example Apps
Various Todo App examples are easy to find. (For example, here: http://rackt.
org/redux/docs/basics/ExampleTodoList.html)
A very thorough, deep dive into Redux, using a Todo App example, from the
creator of Redux (Dan Abramov): https://egghead.io/series/getting-started-with-
redux
Another more complex example, involving asynchronous server requests (fetches
Reddit headlines): http://rackt.org/redux/docs/advanced/ExampleRedditAPI.html
Complex Redux Example
Here’s a very good one, with a lot of detail: http://teropa.
info/blog/2015/09/10/full-stack-redux-tutorial.html
It’s a live voting app, where items to vote on are paired up tournament-
style, and the winners are promoted to the next round against other
winners.
Addresses Immutable, unit testing (with mocha + chai), socket.io
usage, and a few other cool things.
Has a browser app (with React) and a node server app - they
communicate via socket.io.
Converting Flux to Redux
Here’s one instructive approach - see how it was done for a well documented non-
trivial app:
1. Buy and read the React SurviveJS book (https://leanpub.
com/survivejs_webpack_react)
2. Work through its React kanban app code (which uses the Alt Flux
implementation, not Redux).
3. Then, review the Redux port of that kanban app here: https://github.
com/survivejs/redux-demo
Redux Reducers
A reducer is a function which takes an action + state, and produce a new state. DO
NOT mutate existing state! You can use Immutable.js to enforce this. Strongly
suggested to do so, to avoid subtle bugs.
const reducer = (state, action) => {
switch(action.type) {
case ‘ADD_TODO’:
return [...state, {text: ‘new todo’ , completed: false}];
default:
return state; // by default, reducer should just return the state
}
}
Actions / Action Creators
React components send out actions which ultimately change the app state
via the reducers.
Actions contain some sort of payload, as well as some information regarding
their type and whether or not they represent an error of some sort.
Exactly how to organize / structure actions to easily handle error conditions
is a major motivating factor for Flux Standard Actions.
Flux Standard Actions (FSAs)
Motivation: Standard way to handle success / error actions without creating a
bunch of constants like ‘SOME_ACTION_SUCCESS’, ‘SOME_ACTION_ERROR’, etc.
Should at least have:
-type
-payload (may be an Error() object with details, if this represents an error)
-optionally some meta info about the action.
Redux “Smart” vs. “Dumb” Components
● Smart Components (those that know about the Redux store) - the Redux guys
suggest keeping these to a minimum, preferably one for the whole
application.
● Dumb Components (most of them :) ) - do not know about the Redux store.
Completely driven by props from parent component. Dispatches actions in
response to user interaction, which are handled by reducers, which ultimately
may produce a new app state.
More Complex Redux Example
Full-featured Grid in Redux (e.g. react-datagrid is a good choice) - but what would
we keep in the app store to make this a real Redux component? Potentially the
following:
● List of columns to show
● Column widths
● Which columns are sorted, and in what direction
● Selected rows
● Filters
● Scrollbar positions
Useful Redux Modules for Node.js
● react-redux (the core Redux library for React)
● redux-devtools (development tools to easily inspect the Redux store)
● redux-actions (Redux-friendly actions)
● redux-logger (Redux logging middleware)
● redux-thunk (Async support)
● redux-promise (Async support)
● react-datagrid (Full-featured tabular data grid)
● redux-form (Redux friendly forms)
Redux Downsides?
● Can be a bit hairy at times to reach into a complex app state tree and find just
want you want to change for the next state (get used to Immutable’s API for
doing these things)
● Good way to organize actions / reducers is debatable, not so clear? (Here’s
one possible way to do it: https://medium.com/lexical-labs-engineering/redux-
best-practices-64d59775802e#.f7xvv6f4g)
● As it’s a very different way of doing things, can be hard to get people ‘on
board’ with the new paradigm
Redux Resources
● https://github.com/rackt/react-redux
● http://rackt.org/redux/index.html
● SurviveJS redone in Redux - nice complex example:
● Full tutorial using Redux: http://teropa.info/blog/2015/09/10/full-stack-redux-
tutorial.html
● Awesome Redux (quite a long list o’ links): https://github.
com/xgrommx/awesome-redux
● https://egghead.io/series/getting-started-with-redux
Notable React 0.13 + 0.14 Changes
● ES6 style classes now available in 0.13 (so instead of React.createClass(...),
you can do class Foo extends React.Component)
● component.getDOMNode is replaced with React.findDOMNode
● The DOM part of React is split out into a separate ReactDOM package in 0.14,
so that only the core React code that makes sense for things like React Native
are in the React package.
● refs to DOM node components are the DOM nodes themselves (no need to
call getDOMNode - 0.14)
● Additional warnings around mutating props
The Future of React / Redux
Good starting point to look for interesting upcoming changes:
https://github.com/reactjs/react-future
Some highlights:
● Property initializers for state
● Property initializers for arrow functions, simplifying binding-related code
● props, state passed into render method to eliminate the need for ‘this.’
Closing Thoughts / Questions
● Will React eventually incorporate some standard version of Redux?
● Does Redux have enough momentum in the community to commit to?
● Do we even need to bother with Flux anymore?
● Is the Redux ecosystem mature enough for production apps?
● Are the concepts in Redux easy enough for developers to quickly become
productive?
A Bit More About Us (Cielo Concepts)...
● Expertise with complex code conversion projects using modern web
application technologies (e.g. React / Redux)
● Training available for various popular web development libraries /
frameworks (including React / Flux / Redux)
● Design / mockup / usability consulting
● Full stack development with Rails, Java, and other established technologies
● Pattern Lab training / consultation
● Inquire about availability: jeffreys@cieloconcepts.com
Hope This Was Helpful
Will be updating this slide deck often with additional notes from
React / Flux/ Redux / ES6 / Immutable land...

More Related Content

What's hot

Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with ReduxFernando Daciuk
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux jsCitrix
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with ReduxMaurice De Beijer [MVP]
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and ReduxThom Nichols
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React NativeEric Deng
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In MeteorDesignveloper
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorialMohammed Fazuluddin
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobXDarko Kukovec
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit TestingEswara Kumar Palakollu
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 

What's hot (20)

Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with Redux
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
React and redux
React and reduxReact and redux
React and redux
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
Using redux
Using reduxUsing redux
Using redux
 
React js
React jsReact js
React js
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In Meteor
 
Angular redux
Angular reduxAngular redux
Angular redux
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobX
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit Testing
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 

Viewers also liked

Client side rendering using mustache.js
Client side rendering using mustache.jsClient side rendering using mustache.js
Client side rendering using mustache.jsBhashkar Sharma
 
WebPredict Technical Interview Screening Presentation
WebPredict Technical Interview Screening PresentationWebPredict Technical Interview Screening Presentation
WebPredict Technical Interview Screening PresentationJeffrey Sanchez
 
Agile масштабирование компании
Agile масштабирование компанииAgile масштабирование компании
Agile масштабирование компанииTimofey (Tim) Yevgrashyn
 
Масштабирование Agile: Challenge Accepted
Масштабирование Agile: Challenge Accepted Масштабирование Agile: Challenge Accepted
Масштабирование Agile: Challenge Accepted Antonina Binetskaya
 
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)Ontico
 
Introduction to bdd
Introduction to bddIntroduction to bdd
Introduction to bddantannatna
 
Modular development with redux
Modular development with reduxModular development with redux
Modular development with reduxJavier Lafora Rey
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.jsMax Klymyshyn
 
ABR Algorithms Explained (from Streaming Media East 2016)
ABR Algorithms Explained (from Streaming Media East 2016) ABR Algorithms Explained (from Streaming Media East 2016)
ABR Algorithms Explained (from Streaming Media East 2016) Erica Beavers
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps. Emanuele DelBono
 
Forrester Report: The Total Economic Impact of Domo
Forrester Report: The Total Economic Impact of DomoForrester Report: The Total Economic Impact of Domo
Forrester Report: The Total Economic Impact of DomoDomo
 
Scalable Media Workflows in the Cloud
Scalable Media Workflows in the CloudScalable Media Workflows in the Cloud
Scalable Media Workflows in the CloudAmazon Web Services
 
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)Ontico
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingJay Phelps
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Forgotten women in tech history.
Forgotten women in tech history.Forgotten women in tech history.
Forgotten women in tech history.Domo
 

Viewers also liked (20)

Client side rendering using mustache.js
Client side rendering using mustache.jsClient side rendering using mustache.js
Client side rendering using mustache.js
 
WebPredict Technical Interview Screening Presentation
WebPredict Technical Interview Screening PresentationWebPredict Technical Interview Screening Presentation
WebPredict Technical Interview Screening Presentation
 
Agile масштабирование компании
Agile масштабирование компанииAgile масштабирование компании
Agile масштабирование компании
 
Масштабирование Agile: Challenge Accepted
Масштабирование Agile: Challenge Accepted Масштабирование Agile: Challenge Accepted
Масштабирование Agile: Challenge Accepted
 
Mocha.js
Mocha.jsMocha.js
Mocha.js
 
Frontend Operations
Frontend OperationsFrontend Operations
Frontend Operations
 
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)
Масштабирование Agile/Lean разработки в рамках программы (Александр Якима)
 
Introduction to bdd
Introduction to bddIntroduction to bdd
Introduction to bdd
 
Modular development with redux
Modular development with reduxModular development with redux
Modular development with redux
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.js
 
ABR Algorithms Explained (from Streaming Media East 2016)
ABR Algorithms Explained (from Streaming Media East 2016) ABR Algorithms Explained (from Streaming Media East 2016)
ABR Algorithms Explained (from Streaming Media East 2016)
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
 
Forrester Report: The Total Economic Impact of Domo
Forrester Report: The Total Economic Impact of DomoForrester Report: The Total Economic Impact of Domo
Forrester Report: The Total Economic Impact of Domo
 
Scalable Media Workflows in the Cloud
Scalable Media Workflows in the CloudScalable Media Workflows in the Cloud
Scalable Media Workflows in the Cloud
 
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = Amazing
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Forgotten women in tech history.
Forgotten women in tech history.Forgotten women in tech history.
Forgotten women in tech history.
 

Similar to The Road To Redux

Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and ReduxPaddy Lock
 
A React Journey
A React JourneyA React Journey
A React JourneyLinkMe Srl
 
Introduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptxIntroduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptxSHAIKIRFAN715544
 
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malikLama K Banna
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptxSHAIKIRFAN715544
 
Intro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptIntro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptjasonsich
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJSLinkMe Srl
 
FRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and PatternsFRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and PatternsLeapfrog Technology Inc.
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperFabrit Global
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
ReactJS - A quick introduction to Awesomeness
ReactJS - A quick introduction to AwesomenessReactJS - A quick introduction to Awesomeness
ReactJS - A quick introduction to AwesomenessRonny Haase
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming PrinciplesAndrii Lundiak
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Introduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptIntroduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptJohn Stevenson
 

Similar to The Road To Redux (20)

Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and Redux
 
React.js at Cortex
React.js at CortexReact.js at Cortex
React.js at Cortex
 
A React Journey
A React JourneyA React Journey
A React Journey
 
Introduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptxIntroduction to ReactJS UI Web Dev .pptx
Introduction to ReactJS UI Web Dev .pptx
 
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malik
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptx
 
Intro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptIntro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScript
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
FRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and PatternsFRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 
ReactJS - A quick introduction to Awesomeness
ReactJS - A quick introduction to AwesomenessReactJS - A quick introduction to Awesomeness
ReactJS - A quick introduction to Awesomeness
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
BackboneJS + ReactJS
BackboneJS + ReactJSBackboneJS + ReactJS
BackboneJS + ReactJS
 
Introduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptIntroduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with Clojurescript
 

Recently uploaded

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 

Recently uploaded (20)

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 

The Road To Redux

  • 1. The Road To Redux The React + Redux + Immutable + ES6 Combo
  • 2. Notes From My Crash Course In Redux So Far... By Jeff Sanchez, consultant @ Cielo Concepts
  • 3. Why React? ● Fast Rendering Updates (via the much touted “virtual DOM” and associated efficient diff when deciding what to re-render) ● Relatively Easy to Understand (especially in more complex examples) ● Large + Growing Enthusiasm / support from tech giant + community ● Scales Well (especially with the help of additional libraries) ● Easy to Debug (in some sense, there’s not much to go wrong in any given component) ● Flexible - less of a commitment (not really a framework) - use as little or as much of it as you’d like ● Helpful JSX HTML-ish Language ■ (optional, but you’ll probably want it)
  • 4. Feel the React Momentum! (from Google Trends)
  • 5. JavaScript Frameworks/Libraries With Similar Goals, Or Otherwise Mentioned In The Same Conversation As React ● Angular / MEAN stack ● Ember ● Backbone ● Ext JS / Sencha ● Polymer ● Meteor / Blaze ● Knockout ...And many more lesser known ones. Of the ones I’ve tried, React has been the easiest (at least, for rapid prototyping). Also appears to have more momentum than these do.
  • 6. The Oft Done Angular Comparison Angular ● Two-way data binding ● Fairly heavyweight framework ● directives, controllers, services ● Can be hard to reason about the flow in some more complex examples ● Inject data via scopes ● More intuitive looping constructs (arguably) ● Backed heavily by Google ● Large established ecosystem React ● Uni-directional data flow (Flux pattern) ● Easy composition / nesting of components ● High performance via virtual DOM ● JSX syntax (optional) ● Inject data via props ● Backed heavily by Facebook ● Context switching in JSX land can be jarring ● Smaller ecosystem, though growing fast
  • 7. Our 10,000’ View is… ● React, for easy componentization / organization of UI elements ● ES6 (ECMAScript 6), for more elegant, easier to read JavaScript code ● Redux, for predictable, manageable application state ● Node.js for many supporting modules for JavaScript SPAs ● Immutable, to help enforce the “Redux Way” (and thus reduce bugs) ● Webpack + Babel, for bundling, hot reloading, JavaScript ES6+ language features, etc. ● Pattern Lab, for our ‘living styleguide’ / atomic design approach
  • 8. Steps For Developing A React App From the Facebook React docs, here’s one suggested approach: 1. Initially, start with a mockup of what a particular page should look like 2. Break the UI into a component hierarchy 3. Build a static version in React (i.e. don’t use state at all yet) 4. Identify the minimal, complete version of the state of the UI 5. Determine where the state should live, at a component level 6. Add inverse data flow as needed (data flowing from components deep in the hierarchy to ones closer to the top)
  • 9. The React Approach, Cont. Create components that can be easily composed into larger components, ultimately making up views. Components can maintain their own state, and/or can instead have it driven via “props” from parent components Flexible, less opinionated library + optional expanding ecosystem === use as little or as much of the React world as you’d like. Unidirectional flow makes debugging / reasoning about app behavior easier - it’s one of the main differentiators between React and Angular.
  • 10. Some React Basics ● Component properties are passed from parent component to child, read-only from child’s point of view ● Component can maintain internal state via ‘state’ property ● render method outputs React DOM (virtual DOM) elements to be transformed into actual DOM elements by React ● Lifecycle methods provided before/after rendering for components ● Easily inline styles with style objects ● Components can contained nested components, and reference other components via refs ● JSX syntax makes component rendering easier to follow
  • 11. Many Useful Node.js Modules in React ecosystem Thankfully, there are well tested React/Redux components and associated Node modules (check out npmjs.com, react.rocks, and react-components.com) for: ● Grids (react-datagrid) ● Tabs (react-tabs) ● Forms (redux-forms) ● Modals (react-modal) ● Actions (redux-actions) ● Logging (redux-logging) ● Routing (redux-simple-router) ● Asynchronous requests (redux-promise, redux-thunk) ● And many more!
  • 12. A Bit About React’s JSX language... JSX is a JavaScript extension that looks similar to XML. It’s optional in React, but is encouraged and used quite a lot. Why? JSX is an easier, more readable syntax for laying out nested component UI. Typically, you’ll find it in the render method for a React component, when returning what to render. For example: render () { // JSX - note the JS expression referencing prop values: return <div>Hello {this.props.name}!</div>; }
  • 13. ES6 - The JavaScript We’ve Been Looking For Coming from a Java background myself, some of these changes are quite comforting: ● Class syntax ● Module import ● Arrow functions (similar to lambda expressions in Java 8) ● Destructuring ● Rest Spread operator ● Improved iterators ● Template strings
  • 14. ES6 Highlights Arrow functions are particularly useful, succinct language additions: E.g.: ES5 “old way” (var and function keywords): var nums = [1, 2, 3, 4, 5, 6]; var squares = nums.map(function (x) { x * x)); Rewritten function with ES6 arrow functions: let squares = nums(x => x * x);
  • 15. ES6 + React Usage ES6 classes + constructors + module imports work nicely with React: import React from ‘react’; export default class Book extends React.Component { constructor(props) { // possibly set up state here, bind functions, etc. } render () { return ( <div className=”book”> <BookSummary id={this.props.id} /> <AuthorBio name={this.props.author} /> </div> ); } }
  • 16. More ES6 Slickness Destructuring examples, both for arrays and objects: let arr = [1, 2, 3, 4]; let [first, ,third] = arr; // first === 1, third === 3 let person = {firstName: “Mike”, lastName: “Smith”, age: 30}; const {firstName, age} = person; // firstName === “Mike”, age === 30 Pretty common to see this pattern at the top of render() methods in React/Redux components: render () { const {dispatch, someProp, anotherProp} = this.props; }
  • 17. Motivations for Flux (which is…?) We should address Flux a bit before talking about Redux: Flux addresses component state management for more complex React applications. Technically, it’s just a pattern of uni-directional data flow development embraced by React. (There are various implementations of Flux.) Improves code management moving the storage outside of the component.
  • 18. More Flux Overview State is moved to stores, components dispatch actions to the stores via the dispatcher, and their rendering is (mostly) driven by props. Controller-views (typically, top level components) receive change events emitted by stores and update their state and their children’s state appropriately. The Flux flow looks like this: ACTION DISPATCHER STORE ACTION VIEW
  • 19. Flux Implementations ● Alt (pretty popular - see SurviveJS leanpub book for some good examples) ● Flummox (apparently nearing end of life) ● Reflux ● Facebook’s Flux ● Fluxxor ● … Some more obscure ones with “Back to the Future”-related names... ● Redux (Not exactly Flux, as we’ll see...) More complete Flux implementation list with some demos: https://github. com/voronianski/flux-comparison
  • 20. Redux - Not Exactly Flux Motivation: How best can we make state mutations predictable in SPAs (Single Page Applications)? Can we support hot reloading / “time travel” debugging / middleware better? Redux answer: impose restrictions on how / when we can make these state mutations. Their 3 principles: ● Single source of truth ● State is read-only ● Pure functions transform state + action into new state
  • 21. Redux Benefits ● Hot reloading (don’t lose app state after a code change in a running app instance) ● Time travel debugging (revert to an older application state just by replacing the current state with an older application state snapshot) ● Centralized application state tree (“single source of truth”) - easy to drill down into when debugging. It’s just a big tree data structure (of maps, lists, sets). ● No need to manage multiple stores like in Flux implementations. ● Minimal size (2K!) and simple API.
  • 22. Redux Concepts ● Actions - created and dispatched to the reducers, which typically produce a new app state ● Reducers - take state + action, and produce the next state ● Store - place where entire application state is stored ● Data Flow - unidirectional (view -> action -> store -> view) ● Thunks for Async actions (cannot have side effects in reducer pure functions) ● Immutability (correctness and performance reasons) ● Middleware (e.g. logging) ● No dispatcher (unlike Flux)
  • 23. Immutable and Redux Problem: how can we prevent inadvertent state mutations, which could cause subtle bugs in the Redux world? Answer: enforce immutability by using Immutable.js or similar library Immutable provides data structures such as Sets, Lists, Maps that cannot be mutated. Instead, data structure methods that look like mutators actually return new instances of the data structure they operate on (e.g. set.add(‘something’) returns a new set with ‘something’ added to the original set).
  • 24. Immutable Benefits ● Performance boosts in part due to comparison via === (as opposed to deep comparison) when React needs to determine what should be re-rendered. ● Enforces the Redux state immutability concept, thus reducing bugs ● Pretty powerful data structure library for manipulating Sets, Lists, Maps, etc. ● Well tested / supported ● Painlessly convert to/from ordinary JS objects (with toJS()/fromJS())
  • 25. Redux Utilities / Related Modules ● redux-logger - easy to use logger middleware ● redux-actions - help organize your redux actions ● redux-thunk - asynchronous support (e.g. for AJAX requests) ● redux-router / redux-simple-router - routing support (map paths to components) ● redux-promise - promise support ● redux-devtools - debugging tools (easily navigate current state of redux app state) ● redux-form - nice form support, particularly around validation
  • 26. Useful Redux Example Apps Various Todo App examples are easy to find. (For example, here: http://rackt. org/redux/docs/basics/ExampleTodoList.html) A very thorough, deep dive into Redux, using a Todo App example, from the creator of Redux (Dan Abramov): https://egghead.io/series/getting-started-with- redux Another more complex example, involving asynchronous server requests (fetches Reddit headlines): http://rackt.org/redux/docs/advanced/ExampleRedditAPI.html
  • 27. Complex Redux Example Here’s a very good one, with a lot of detail: http://teropa. info/blog/2015/09/10/full-stack-redux-tutorial.html It’s a live voting app, where items to vote on are paired up tournament- style, and the winners are promoted to the next round against other winners. Addresses Immutable, unit testing (with mocha + chai), socket.io usage, and a few other cool things. Has a browser app (with React) and a node server app - they communicate via socket.io.
  • 28. Converting Flux to Redux Here’s one instructive approach - see how it was done for a well documented non- trivial app: 1. Buy and read the React SurviveJS book (https://leanpub. com/survivejs_webpack_react) 2. Work through its React kanban app code (which uses the Alt Flux implementation, not Redux). 3. Then, review the Redux port of that kanban app here: https://github. com/survivejs/redux-demo
  • 29. Redux Reducers A reducer is a function which takes an action + state, and produce a new state. DO NOT mutate existing state! You can use Immutable.js to enforce this. Strongly suggested to do so, to avoid subtle bugs. const reducer = (state, action) => { switch(action.type) { case ‘ADD_TODO’: return [...state, {text: ‘new todo’ , completed: false}]; default: return state; // by default, reducer should just return the state } }
  • 30. Actions / Action Creators React components send out actions which ultimately change the app state via the reducers. Actions contain some sort of payload, as well as some information regarding their type and whether or not they represent an error of some sort. Exactly how to organize / structure actions to easily handle error conditions is a major motivating factor for Flux Standard Actions.
  • 31. Flux Standard Actions (FSAs) Motivation: Standard way to handle success / error actions without creating a bunch of constants like ‘SOME_ACTION_SUCCESS’, ‘SOME_ACTION_ERROR’, etc. Should at least have: -type -payload (may be an Error() object with details, if this represents an error) -optionally some meta info about the action.
  • 32. Redux “Smart” vs. “Dumb” Components ● Smart Components (those that know about the Redux store) - the Redux guys suggest keeping these to a minimum, preferably one for the whole application. ● Dumb Components (most of them :) ) - do not know about the Redux store. Completely driven by props from parent component. Dispatches actions in response to user interaction, which are handled by reducers, which ultimately may produce a new app state.
  • 33. More Complex Redux Example Full-featured Grid in Redux (e.g. react-datagrid is a good choice) - but what would we keep in the app store to make this a real Redux component? Potentially the following: ● List of columns to show ● Column widths ● Which columns are sorted, and in what direction ● Selected rows ● Filters ● Scrollbar positions
  • 34. Useful Redux Modules for Node.js ● react-redux (the core Redux library for React) ● redux-devtools (development tools to easily inspect the Redux store) ● redux-actions (Redux-friendly actions) ● redux-logger (Redux logging middleware) ● redux-thunk (Async support) ● redux-promise (Async support) ● react-datagrid (Full-featured tabular data grid) ● redux-form (Redux friendly forms)
  • 35. Redux Downsides? ● Can be a bit hairy at times to reach into a complex app state tree and find just want you want to change for the next state (get used to Immutable’s API for doing these things) ● Good way to organize actions / reducers is debatable, not so clear? (Here’s one possible way to do it: https://medium.com/lexical-labs-engineering/redux- best-practices-64d59775802e#.f7xvv6f4g) ● As it’s a very different way of doing things, can be hard to get people ‘on board’ with the new paradigm
  • 36. Redux Resources ● https://github.com/rackt/react-redux ● http://rackt.org/redux/index.html ● SurviveJS redone in Redux - nice complex example: ● Full tutorial using Redux: http://teropa.info/blog/2015/09/10/full-stack-redux- tutorial.html ● Awesome Redux (quite a long list o’ links): https://github. com/xgrommx/awesome-redux ● https://egghead.io/series/getting-started-with-redux
  • 37. Notable React 0.13 + 0.14 Changes ● ES6 style classes now available in 0.13 (so instead of React.createClass(...), you can do class Foo extends React.Component) ● component.getDOMNode is replaced with React.findDOMNode ● The DOM part of React is split out into a separate ReactDOM package in 0.14, so that only the core React code that makes sense for things like React Native are in the React package. ● refs to DOM node components are the DOM nodes themselves (no need to call getDOMNode - 0.14) ● Additional warnings around mutating props
  • 38. The Future of React / Redux Good starting point to look for interesting upcoming changes: https://github.com/reactjs/react-future Some highlights: ● Property initializers for state ● Property initializers for arrow functions, simplifying binding-related code ● props, state passed into render method to eliminate the need for ‘this.’
  • 39. Closing Thoughts / Questions ● Will React eventually incorporate some standard version of Redux? ● Does Redux have enough momentum in the community to commit to? ● Do we even need to bother with Flux anymore? ● Is the Redux ecosystem mature enough for production apps? ● Are the concepts in Redux easy enough for developers to quickly become productive?
  • 40. A Bit More About Us (Cielo Concepts)... ● Expertise with complex code conversion projects using modern web application technologies (e.g. React / Redux) ● Training available for various popular web development libraries / frameworks (including React / Flux / Redux) ● Design / mockup / usability consulting ● Full stack development with Rails, Java, and other established technologies ● Pattern Lab training / consultation ● Inquire about availability: jeffreys@cieloconcepts.com
  • 41. Hope This Was Helpful Will be updating this slide deck often with additional notes from React / Flux/ Redux / ES6 / Immutable land...