React.js Conf Notes – Day 2

React Native

3 pillars
– Touch handling (biggest difference between native and mobile web)
– Native components (there is a lot existing native components, and the mobile web framework should provide something comparable)
– Style & layout ()

Native Components:
RKView extends from UIView. It converts DOM commands to native. The only work done in the main thread is setting the view, all others are offloaded.

Internally, it run a real JS engine, using JSCore this time. All js modules that don’t depend on the browser will work. Showed running js remotely in Chrome, with websocket communication between iOS simulator between Chrome, could run js remotely in the future, or run js remotely in the server. Crazy idea: what if server-side render native views..

-Styling

React: CSS in JS, speakerdeck.com/vjeux/react-css-in-js

Style Declaration in JS with Inline Styles

Instead of separating technologies (JS/CSS), we need to separate concerns

Layout: top,left, width, height
IOS -> manual mode -> auto layout (constraint solver)
CSS -> margin, padding, border
Flexbox -> life changing

NO browser in native env -> need to reimplement a subset of flex box in ReactNative
Generate random tests -> send it to browser and ReactNative implementation -> compare and extreme TDD

Only implemented a subset of Flexbox

iOS? The bridge between JS and Objc-C is async, batched, seriablizable. Async is very problematic.

Also ported the flexbox implementation in C and Java, and open sourced at https://github.com/facebook/css-layout


Web components
Web components -> html elements encapsulable and portable

Intro to custom elements / Shadow DOM

web component for react
– small
– extremely encapsulated, no side-effect
– stateless
– performant

Custom events need to attached and detached manually

The future
– custom attribute support
– custom event


Lee Byron, Immutable Data in React & Flux

immutable.js

How? Why?

Persistent immutable data structures

persistent(not related to write to disk, but leave the old one unchanged)

Isn’t deepclone really slow? Well, isn’t re-render the whole UI slow?

Interface vs implementation

implementation – structural sharing – directed acyclic graph
directed – references
acyclic – no going back

an version of DAG – Index Trie (List), Hashed Trie (Object)

Legendary people:
– JCR Licklider
– Alan Kay – ‘the early history of smalltalks’
– Phil Bagwell
– Rich Hickey – Clojure – Simple made easy – 2011

Mutable objects are complicated in identity, time and space. Immutable data removes complexity

The many mutators problem. But what changed?
– ES7 – Object.observe(), only one level deep
– Immutable change tracking and memoization

Om is faster than React! Immutablity has constant penalty(3-5x) with log(n) memory but can change some ops from o(n) to o(log(n))


Beyond the DOM: How Netflix plans to enhance your television experience #

Jafar Husain, cross-team leads for UIs

Three things you don’t know about Netflix:
1. loves js, runs thousands of devices, and js has the reach. A/B testing with js can break out the App Store constrains
2. super secret TV platforms. Netflix TV platform. 2-3 years ago, webkit + web app in the TV. DOM is slow.
3. love React.

Netflix TV platform – Gibbon
– get rid of DOM. Use widget object model instead of DOM
– use js instead of js/html/css
– Web is different from TV.
Flow layout -> absolute position
many types -> one type
400+ props -> 25 props
sync -> async
inherited styles -> explicit styles

Gibbon on HTML canvas
– three UIs(mobile.js, web.js, tv.js) in 2013 now two UI (mobile.js/web.js into one, tv.js use Gibbon)

Love react
– one year now
– two reasons, performance and simplicity(one way data flow, server side rendering, even for TVs)

The challenge for team – use React with Gibbon in 5 days

Option one – fork React
Widget Adapter Mixin, convert widget to DOM-like

DOMPropertyOperations
ReactDomComponent

Create markup string
– mountComponent
– createMarkupfor

Object.assign??(ES6)

React Fork:
– dev days 2
– forked loc 67

Option two – spoon react
– monkey patch
– react-art
– react-ios
– react-pixi
– react-three

React for total different

new mixin based on ReactMultiChild
overwrite
– moveChild,
– createChild
– removeChild

Continue working on the TV version of React. Netflix likes React the blog post. RenderToCanvas is closed source, but react-art is a good starting point.


Zach Nation, Dato

Dynamic Web UI

Data visualization (Graphlab Canvas)

two things
– turn data into visual elements
– handle rendering

Build a predictive application
data -> relevant info -> build a model -> deploy the model

Human beings are good at visual pattern recognition

Example: bitcoin transaction

21G data, sequentially arranged, 45M transactions

Challenges:
– Large data to visual elements
– High level of interactivity
– Maintain state across the whole-app UI

Pipeline:
Data -> aggregation -> d3.js (produce visual elements) -> rendering (react.js)

– compute close to the server
– Flux on the server, replace dispatcher with XHR / WebSocket

Cons: it’s a single user server

Scalable aggregation
– binning, histogram in 1d and heatmap in 2d
– sketch data structures
– constant memory complexity
– produce results incrementally (streaming). Important for UI/UX
– send results to client periodically

Example:
Server owns the state -> web socket -> component setState -> re-render

Visual elements correspond to React component
– text values are data
– D3.js complement React

Three parts of d3 conflicts with React.js
– Selections(d3 core)
– Transitions(d3 core)
– d3.behavior

Chose a render target
– svg
– canvas
– react-art
– webgl
– ios
– android

Considerations
– number of visual elements (canvas better)
– animation
– level of interactivity
– browser support

Svg vs Canvas
– SVG: css styles, css animations, DOMEvents
– both: 1000 or fewer elements
– Canvas: 1000+ visual elements

The Graphalab canvas
– 100% React rendered with stateful-server
– up to 1TB data streaming down

Server – Aggregation

Client – React.js

github.com/znation


Om – David

Closure language
ClosureScript -> dialect of Closure targets JavaScript

Context:
– unfamiliar != complex
– big != complex

React as platform
– Platform, not about solution, about process
– Pick bricks as the tool, build both regular house and amazing buildings

The reason: other frameworks pick mutability, React works with both mutable and immutable data. Mutability should be an implementation detail

OM, based on a paper by Alan Kay

Design
– immutable app state
– async rendering via requestAnimationFrame
– jumps to any point of time with respect of application status
– modularity

How do you hide data from components that they shouldn’t know yet still keep it global..
– lens or windows, only returns a slice of the global state to the component
– this solves 60% of the problem

Reference cursor, same cursor but observable
– same as event listener, just observe
– allow OM components to listen on data changes

There is nothing fundamentally wrong with observation.
– after normal render of the component tree from the root, walk list of reference cursors to see if they are changed. if changed, force update
– CircleCI demo, 10 – 15k line of closure script

Interesting UIs are inherently complex…

Immutability identify sources of incidental complexity

Bad part:
– custom tag that isn’t React key or constructor function
– expose React component tree as data to support custom tree transformations (like a compiler, expose the tree as data)
– regular JS classes

Why React?
– not because of virtual dom
– but because of DOM virtual machine / UI virtual machine


Flux Panel by Bill Fisher

Relay are more for big teams with big apps. Flux is for a much wider audience. There is a migration path from Flux to Relay. You could have both of them in the same app.

Data fetching:
– Only call getData in the store, 100+ stores, and 60+ need to fetch data. Moved the data fetching into the store, if not there, the store will get it and put it to the store cache. When updating, it is nice to have all data fetching in one place. Consumers of the store don’t have to change.When building new request for data, sometime you need the existing data which is exactly in the store. It is natural to construct the request from within the store.

– Everything goes through the data the same way. All of our writes are in the action creator. Action creators are async, promised based. Good for optimistic updates. Why in actions? Because different stores might need the result of the action.

Kyle:
– performance in large app (106 stores)
– dispatcher is sync
– interface becomes laggy for few reasons
– have two stores responding to the same action, then both store will emit a change, when controllers listen to both stores, it will re-render twice for the same action.
– when loading the page, 200+ actions, when change, 80+ actions. The easy optimization is to debounce the call based on the dispatch loop, wait for the loop finish. 75% reduction in # of actions.

Very few dependencies in store (90+ stores)
– when store has lot of dependencies. Components are responsible for dependencies. Component will get data from store A and send it to B. Component will declare that for this field in my state, here is the data that field depends (graphQL). When any prop changes, figure out whether the depending data changes.

Large app:
160+k loc, 10+ engineers
700+ components
– Component is the best way to maintain a large codebase.
– Keep store from each other. Thread store and Message Store. Keep data separate. Normalize all the stores, similar to a database.

Isomorphic flux
– soudcloud store singleton
– yahoo store instances

Take actions, call them on the server, and hydrate the store on the server. Make store classes and fill their instances per request. Ability to test easily.

Dehydration and rehydration. Create store instance per request, has a request context per request, has a dispatcher, at the end of execution, gave all the store on the server, let’s dehydrate and serial down the client, and rehydrate the app on the client

Singleton store. You could run into con-current issues. We don’t use flux to fetch data on the server side, a helper do it and pass the data to the action. A pure action that based on the same data. The client will take an extra step, first pass, and the second pass for client specific stuff.

Andres, Scala backend, browserify the app and get a platform agnostic version. Run the app in a Java based JS runtime(?), and spit out html. Very render-oriented approach.

Michael, stateful, mostly fetching logic in the actions

Airbnb
– migration from Backbone/handlebars to React
– biggest app is mange listing app, allowing host to manage properties
– Pick a part of the backbone view and replace it with React
– Wrap model/collections with store, introduce actions. A thin wrapper!
– Compared to backbone, now we have clear entry point for data fetching

What is the dispatcher in Airbnb:
– AppModel(from Backbone days), reuse the global dispatcher as the flux dispatcher. We inject the AppModel into different places.
– One thing missing is the waitFor method. So far we haven’t had any need for waitFor, but might need it in the future.

Optimistic update and error handling:
– maintaining a clientId?
– actions queue in Relay is interesting
– When merge the update without confirmation from the server, you lose the previous state. Actions queue keep a separate queue of actions, if an error comes in, can take the action out of the queue, if confirmed, can take action out of the queue. All views get data from store + queued updates.

Routing:
– route at the store level
– no change route or change route methods
– route store will change, will decide what component need to render at the root component.
– route store becomes the ultimate store!

Q: decouple actions from store?
A: container component + UI component. container’s job is to talk to store and get the state, no state in the UI component.


Codecademy’s approach to component communication by Bonnie Eisenman

– communication needs
– what we did
– what could be better

Rebuild six month ago.
https://www.youtube.com/watch?v=U5yjPG5mHZ8 Why react from codecademy?
– server side rendering

learn react
– sample code from khanacademy
– react tutorial

Communications:
– callbacks everywhere

Comm need:
– pass state changes to siblings, cousins
– adjust to changing comm targets
– A lot are responding to client actions in the client side

What we did:
– Adapters, always has one,
– Major components, listen to events broadcasted
Major component -> brodacts – > adapter (<=>backend) – > set state

Major Components:
– Tester
– Browser
– ContentEditor
– CodeEditor
– Instructions

Adapter = state dispatcher

Create adapter based on what components are present. When components changes, re-generate adapters.

Defining an adapter:
– Files for any combination of components
– Used to do mixins

Under the hood:
– adapter.js
– create, destory, handle,
– create.js
– only 120 loc
– hook into componentDidUpdate

What are we doing wrong?
– outside manipulation of state???

Adapter vs flux?
– no concepts of stores. Getting data from server is not a pain point
– major components – controller views

Food for thought?
– just the view?
– how should a data flow pattern like Flux be treated in the React docs
– what do you want from your data flow architecture?

Code sandboxing:
– each user has their own box (docker I assume)


Static typing with Flow and TypeScript, James Brantly from AssureSign

Why need type?
0 * ‘123′
‘0’ + ‘2′
– good at first pass
– if add first:number, second:number , then get type checking at build time

Demos
– webpack
– jsx loader

TypeScript:
– it doesn’t understand JSX (stop using jsx / fork TypeScript / hack)
– hack, make JSX a string, React.jsx(“), jsx add a precompile step, convert React.jsx(`

’) to React.createElements()

– syntax changes from js to ts:
— import instead of require
— exports instead of module.exports
— TypeScript definition files, similar to c header files, _references.d.ts
— references path at the top of each file
— remove mixins because ES6 classes don’t support mixins

Flow
– native react support
flow init -> create flow config file -> fix require calls,
flow (cli)
annotate /* @flow */
return any as type annotation

– jsx loader ? strip types

Integrate with flow is much faster than TypeScript

Flow
-understand props
-understand props in jsx

Flow:
– native react
– better type inference

TypeScript:
– works on windows
– lots of definition file

typed-react


Q&A

CSS layout, inline styles, this version is really for react-native

Q: react in other languages?
A: Facebook iOS components, based on the same React idea, but in objective C

Q: rendering mechanics but not enough server sider rendering?
A: Relay has different modes. One mode is js + payload; the other mode is html + payload. The server side render is not designed that way. We can avoid auto-binding.

Q: props, state, context?
A: Diff between owner and parent. Owner creates the element. We are changing it to parent based. The concept of context will stay.

Context comes from XHP, several use cases:
– viewer, who are you logged in; used to be a global, but then viewed as your friend. Then who is logged in vs who is viewing? Then passing a new global to a sub tree.
– logging data
– focus and selection are two global UI states, that could be implemented as contexts!!! Don’t use it to pass the props down.

ReactNative, when there are new iOS and new Android, what to do?
– two ways, either wrap or reimplement. For example, the tab bar at the bottom of the Facebook page is a reimplement.

ReactNative?
– not only fast, but also a better / flexible app. At least better declarative API
– can add new functionalities

Views exist in one platform?
– Transfer from one to another

Mixins?
– Mixin is not part of ES6
– 99% is adding subscription to the external data
– Continue use mixing until there is better way

Webpack?
– we don’t use for Facebook.com
– dependency manger
– trans-compilation
– our packager use machine learning, very fancy packager
– 90+% we are hitting cold caching…
– React Native is bundling js for developer experience

Responsive?
– In Relay, defer query, mark the comment box as optional, and it will come down later.

ReactNative?
– rocksdb for caching,

SurveyMonkey?
– cross browser render in web view and web
– keystone.js

Advertisements
Standard