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

React.js Conf Notes – Day 1

Christopher Chedeau / Tom Occhino – Keynote
Where did React come from?
– Born at Facebook Ads Org. Building a bunch single page apps. Pain point: cascading updates -> unpredictable code
– Hypothesis: (data) => (view), just a functional transformation. Every time the data change, re-render the entire view
– Initial reception among Facebook engineers: everyone is ‘this is so fun, but might be slow’, but ‘someone is going to make it faster’, then use it on the like/comment box inside Facebook.com
– After instagram was acquired, Pete make React opensource-able
– 2013 jsconf debut. Feedbacks are “huge step backwards” / “Rethink established best practicesTM”. To make it interesting, Pete Hunt gave a talk titled “React: Rethink best practice”
JSX
– coming from php or XHP. Key features are composable and approachable
XHP
– auto escaping
– composable
– do all the necessary data fetching
What makes React so powerful?
– Virtual DOM?
– Server rendering? (codeacademy picked React for this reason)
– Descriptive warning?
– Custom events system?
His take on why React is powerful
– React wraps an imperative API with a declarative one. In other frameworks, you use imperative code; but in React, you use declarative code. Easier to read and maintain.
– The key is Declarative
– Declarative -> predictable. The power of looking at the code and being able to change it with confidence.
– Predictable -> confidence -> reliability
– “Reacts’ real power lies in how it makes you to write your code”
Components are the fundamental building blocks of our applications!!!! (I agree)
Mobile?
Paper is cool native app.Why not able to do it in a web app?
Basically native environment is more powerful
– ability to parallelism work (async render / web worker doesn’t work)
– sophisticated gesture handing (native good / web not much)
– access to native capabilities ()
The cost is the native environment is more hostile
– native environment is imperative
React Native
– iOS and Android
– Everything on screen is native, but the underlining is completely controlled by JavaScript
— existing solution is sync waiting for js
— better solution is async, and batched
— converting DOM apis to native APIs
div -> <View />
span -> <Text />
img -> <Image />
– putting js in background thread, async display, never blocking the main thread
– Facebook Group is a mixture of native and React Native. Open Source it soon
We don’t want to “write once and run anywhere”!!! Instead, “learn once and write anywhere”. The same team can write iOS one day and Android the next day following the same principles.
What happens next???
Fundamentally change how people think about JavaScript / JavaScript Framework. From Object.observe to immutability

Brenton Simpson – Tweak your page in real time, without leaving the comfort of your editor

Rethink the entire workflow – ebay. Mobile, not simulation, real hardware
CSS
– Live change styles Everyday use a tablet to show 3 screens of iphones
JS
1. from script tags to modules. Endorse web pack. Web pack is awesome blah blah blah ***
2. Don’t reload, replace
Component -> Pops -> Result
React makes you can call render() all the time
Replace the component with another component
Use React-hot-loader, hot module replacement
3. Point your device
– use tools Charles and use DNS spoofing
4. Stop repeating your sever
– what’s role of server? To provide the data to the app.
The role of client? To render the data to UI.
The API is platform agnostic.
Exact same JSX codebase renders everywhere
– difference between server-side and client-side rendering
Titles(in html on server, in js on client)
Links(complete page refresh on the sever / no page refresh on the client )
Data scope(sesession oriented vs client oriented)
– Ambidex
– First render on the server, subsequent pages on the device
– Experimental, <6 months old, needs test,
– The basis for everything web in eBay lab
– Being developed in the open
Recap:
– test on real hardware with a proxy like Charles
– serve is api
Q&A:
Q: Server side singletons?
A: URL tells server what data should be fetched. All the data should be determined by the URL! But haven’t solved the problem / sessions
Q: SOA, server fetches from other services? should client fetch all those services?
A: Reflux

Gurdas Nijor – Unlocking the structure of your React applications with the AST

Static program -> dynamic process
Static nature of React
Static analysis -> analysis based on the code
What makes static analysis difficult?
– In Backbone view, this.$el can be modified at many locations, hence the rendered output is unknown.
– External dependencies,
What makes static analysis easy?
– React component self-contained
– f(state, props) => output
Three ways of using static analysis (only show one below):
– instrumentation of an application, a common theme in CI
– Demo of todo MVC live streaming of changing props
Main Section -> props -> TodoItems
A component wrapper will wrap TodoItems and publish changed to EventEmitter
Fully instrumented meaning wrapping all components
But how do we generalize this transformation?
Compiler:
Source-> Parser -> tree -> Code generator -> output
Source -> Parser(esprima) -> AST -> Code generation (escogen) ->
AST tools:
– Traversal / Query (estraverse / esquery)
– Fragment Parsing (esprima)
– Builder API (ast-types)
– Templates(estemplate)
– Literal
Power of this tool:
– 3D transform of react components
Package transformations:
– web pack’s concept of loaders
– inject runtime dependencies
Recap
– invariant -> build time properties
– a way to instrument React applications
– package this transformation for easy consuption

Daniel Schafer and Jing Chen – Data fetching for React applications at Facebook

How do we get the data from the server to the client in the first place???
Example:
FriendList -> FriendListItem -> FriendInfo
But each one of them need different data, therefore, there are unnecessary data passing through top of the funnel. If changed FriendInfo, then info has to pass all over again…
How do we come to this?
Changes FriendInfo -> changes every component -> changes the server info
The problem is data leaking. There is missing info -> what data is required for each component
Key idea:
– each component specify its own info requirement
– response Shape
– composition, nested data structures
GraphQL: Facebook client app uses for about two and half years,
– stop writing dedicated endpoints
– abstract data from
{
id:
name:
}

-&amp;gt;
{id
name
}

node(1572451031){
id,
name
}

//root call node(){}

node(1572451031){
ide,
name,
birthdata {
month,
day
},
friends.first(1){
cursor,
node {
name
}
},
friends.after(cursorId).first(2){cursor, node{name}}
}


Data fetching inside Flex
Jing
Response shape is specified by GraphQL. Can we specify what need and auto fetch for us?
statics:{
     queries: function(){
      return graphql`
     User {name, mutual_friends{count}}
}

}

//Composition:
${ProfilePic.getQuery(‘user’)},
${FriendInfo.getQuery(‘user’)}
Life cycle: Query -> de-duplicate -> Server -> Data -> Store(central source of truth) -> Views
Store is generic, holds all the graphQL data
Recap:
Relay is the next generation of Flux, rather than components passing props to its children, have components specify its need.
Static view -> query -> server -> data -> store -> views
– Colocation: query and view are specified in the same component
Pain point -> change one thing (over fetching and under fetching)
php -> parent component -> child component
Examples of Relay:
Relay: add one filed in the query and in the render method
Pagination:
this.setQueryParams({count: this.queryParams.count + 5});

statics:

{
     queryParams: {count: 10}
}
Query validation:
– graphQL provides schema to verify at transform time
Mutations:
– Adding comments
– Take updates and merge and update the central store
– Relay, subscription updates at the component level
Optimistic updates:
– seperate queue for updates
– keep it in the queue until the server confirms
– the error handling is built automatically
Error handling:
Response out of order:
What is next?
– Experimental
– OpenSource graphQl and Relay as soon as we can

James Long – Communicating with channels

– Explain channels
– Integration with channels
– Flux
Talked about js-csp and live demo. (unable to take meaningful notes since I don’t know enough about this topic)

Michael Jackson – Removing User Interface Complexity, or why React is awesome

Michael – OnDemand Valet serivice in LA / mustache /react-router
Removing User Interface Complexity, or why React is awesome
Flow is ember the biggest strength
PHP partials -> assemble the case
Ember -> declarative composition inside each route
“If your user interface is nested, your routes should be nested”. But NestedRoutes != nested URLs
URLs (Ember’s philosophy)
– URL should capture all the information related to that route
– URLs should be part of your design process
Transitions
– when URL changes, what happens…
– A common use case: remember the destination, redirect to login, then continue to the original destination
– Transition redirect and transition retry
– willTransitionFrom. When user is trying to leave an un-submitted form, prompt the user to confirm
– transition.abort();
Demo
mixin -&gt; Authentication
Authentication
willTransitionTo(function(){
 if(not logged){
     Login.attemptedTransition.
     transition.retry();
}
})

The future
– ES6 classes
– Not just JSX
– Sub-routers???

Pete Hunt – The future of JavaScript layout systems

… is probably not GSS (great style sheet). Interesting abstraction, but solvers are unpredictable.
Full-Stack Flux
– A review of Flux
– The current state of the backend
– How Flux can save us
A review of Flux
– Facebook Chat, ship fast and maintain reliability.
– Talk about the problem, how adding new features adding more code to maintain
– Shared mutable state is the root of all evil. The alternative is Observable
– Flux can scale to answer many questions
What about backend?
function getPhoto(){
  get from cache
  if(){
    get from db
    add to cache 
  }
}


Similarly, caching some derived data ?(Ember.data derived data)
What is a Flux Store?
– Reduce() and emit a change event
– Derived data (cache/search index/data warehouses)
– Your app is the derived data
The idea:
Actions -> RabbitMQ(dispatcher) -> getPhoto(photoId) (Store)
                                \——> getMostLikedPhoto(photoId)
 |                                              |
app  <- dispatcher    <-      Action
Message queue (equivalent to a dispacher, but distributed)
Advantages of messageQ
– ***
– has all the state
– most important, manage the tradeoff
Choose the best data store for your question
– schemaless or not
– write
– read
– query flexibility
– costs
– durability
Closing the loop
– Rather than asking the store all the, subscribe to queries on db
Things don’t work
– communication between stores, in particular waitFor()
Option 1: shared DBs between two stores, image classifier to mark whether an image should be blacklisted
Option 2: Enrich data
– image object -> slow running classifier -> enrich the action and add isBlackListed field
– Directed async graph, hook the output of one store to another store
– Forget about strong consistency, adopt an eventually consistent system
– Kafaka should be a better choice
Stream processing on the server, Apache
Recommend to watch “turning the database inside out”
Advantage:
– don’t know what question we need to answer so far.
– it’s not too often that we need multiple stores to answer one question. If two stores are coupled too much, then merge them.

Jason Bonta – Building performant React apps

Works for Facebook Ads. Ads creation gives birth of React.
Ads Manger need to be simple yet powerful. Simple for most users who don’t think them as advertisers, they are small business owners. Powerful for enterprise users, should have native look and feel for tens and thousands of ads.
Ads Manager
– css perf
– GPU acceleration
Optimization ideas:
– props and state
– pure components, the render is only based on props & states
– re-render is the key, shouldComponentUpdate
– mixins: [PureRenderMinx], separate your pureComponents from others
— data comparability, only shallowEqual, problematic for Date() or even functions
— inspired by how people return goods at the brick & mortar store by verifying receipt and sealed product
— data comparability, from a single source of truth (sealed object)
— immutability / immutable.js => referential equaly => fast
Controlled scrolling example
– <Container><Table /><Container />
– event hander on the wheel hander
– components move the content up and down -> change offsetTop
– Separate table code from the scrolling container code -> separation of concerns -> also perf. Scroller changes all the time, but the table code doesn’t change much.
Children create deep update trees
– The more nodes, the slower the diff
– If passing props many levels down, then tightly coupled
Children change over time
– Children is not comparable, can’t compare this.props.children !== next props.children
Children are expensive
Independent children
– not relying parents to pass things to children
– PureRenderMixin
– shouldComponentUpdate just return false
Policy inside FacebookAds
– <Container> <Widget/></Container>
– any data fetching component need to be a container. container talks to the store
– Widget just render
– Container vs components. The point is — container is the data layer!!! You got insulation. When you use the containers, you can move them because they don’t depend on anything!!!
Advantage of Container + Widget
– separate data from presentation
– very easy to show them in the component library
– very easy to test
Components are the foundamental building blocks.
Ads manager:
Every single cell is a speperate APP.
Recap:
– purity, use shouldComponentUpdate and PureRenderMixin
– data comparability (highly comparable data, immutability)
– loose coupling, smaller apps, maintain and performance
– children, expensive and exercise independent (use containers)
<FixedDataTable /> —> open sourced UI component
facebook.github.io/fixed-data-table

Eric Ferraiuolo – React.js & i18n

The problem:
– Localization, 1.002’s meaning depends on the locale
– English is only 5.2% speaking and 27% internet users
The i18n problem:
– Pluralization
– Formatting of the date
– 1 people liked this vs Eric and 1,200 more people liked this
– Relative time
The formation aspect of internationalization
– moment.js for dates related things
– i.e. how to format number with 1,000
ES5.1 has
– Intl.NumberFormat
– Intl.DateTimeFormat
– Intl.Collator
– Missing from Safari but can be polyfilled by intl.js
– the usage
new Intl.NumberFormat().format(1000)
new Intl.DateTimeFormat({
     month: ‘long’,
     day: ‘numeric’,
     year: ‘numeric'
}).format(Date.now())
– need to cache
– and imperative
In React, React Intl (npm module), declarative
String messages (ICU):
“hello, {name}”
“You’re {age, number} years old”
Pluralization
var msg = `{num Comments, plural, one {# comment}, other {# comments}`
<FormattedMessage message={msg} numComments={1200}/>
Intl Mixin
– Add [IntlMixin] at the top of the app and it will cascade to all children
React Intl
– 7.7k min + gz
– 150+ languages
– English as default
Bigger project, format.js, one of the child project is React Intl, one for handlebar and one for dust and one for ember.
Archtetrue:
– Format.js integrations
– Format.js Core
– JS Runtime (Int.*)
– ICU (International Components for Unicode)
– CLDR (Unicode Common Locale Data Repository)
Endgame, eventually propose this and add it to ES
– Intl.MessageFormat
– Intl.RelativeFormat
Q:abbreviate numbers in different locale
A:no idea. Data does exist in CLDR, but not implemented it.
Q:i18n and formated HTML string
A: formatMessage with a simple placeholder. If name is to be bold. Pass react element as value
The other way – HTML message component, escape all html and do dangerousInnerHTML

Ryan Florence – React let you say YES

– Personal story. Sold life insurance in Idaho. Got so interested in software that he spent all his down time writing software. First developer job at an agency and the boss commented that “it’s so weird that a developer keeps saying yes.”
– Developers want to say yes, but often says no because of lack of good tools. React let you say yes more often.
Demo
– live updating tables, ember memory leak, give up at 100; timeout0, react works but ember/angular broke
– magic move
– react-a11y, react’s declarative nature make the assertion possible
– portal, stop the render tree, use jQuery, then use React.render to build another tree
– router animations, use React
– iTunes, route with openning children
Disclaimer: personal notes. Might misunderstand the presenter.
Standard

HTML to PDF with client side JavaScript

I knew PDF viewing is hard, hence the excellent pdf.js library. I didn’t know converting HTML to PDF on client side is also hard.

Converting HTML to PDF on the server side is not bad. You could use wkhtmltopdf or PhantomJS. There is even a blog post with benchmarks.

There are few choices on the client side. One is HTML -> canvas -> image -> PDF. You can create PDFs with jsPDF or pdfkit, but you would have to render the HTML yourself and feed it to jsPDF/pdfkit…

Standard

Deal with dragEnter and dragLeave events

dragEnter and dragLeave have the same problem as mouseIn and mouseOut events – if the drop target has children elements, dragEnter and dragLeave events fire when your mouse is crossing boundaries of those children elements.

The solution? One is pointer-events:none for the children elements. The other is to manually count the dragEnter (counter++) and dragLeave events(counter–), and declare a true mouseLeave only when the counter returns to zero.

HTML5 drag and drag API are pretty tricky to use …

Standard

Firebase One-to-N

Have been using so much Firebase and tried different ways of doing One-to-N. I found this paragraph from Mongo summarized it well.

Embed the N side if the cardinality is one-to-few and there is no need to access the embedded object outside the context of the parent object
Use an array of references to the N-side objects if the cardinality is one-to-many or if the N-side objects should stand alone for any reasons
Use a reference to the One-side in the N-side objects if the cardinality is one-to-squillions

Standard