Right click to open menu
React.js Conf 2015 Notes

Menu bar

Quick Actions

Ribbon

Insert:
Error: Internet connection appears to be offline (0)

Outline

React.js Conf 2015 NotesLink to heading
WednesdayLink to heading
KeynoteLink to heading
Tweak Your Page In Real Time, Without Leaving The Comfort Of Your EditorLink to heading
Unlocking The Structure Of Your React Applications With The ASTLink to heading
Data Fetching For React Applications At FacebookLink to heading
Hallway ConversationsLink to heading
Communicating With ChannelsLink to heading
React-router Increases Your ProductivityLink to heading
The Future Of Javascript Layout Systems Full-stack FluxLink to heading
Making Your App Fast With High-performance ComponentsLink to heading
Format Data And Strings In Any Language With Formatjs And React-intlLink to heading
Hype!Link to heading
ThursdayLink to heading
Keynote - React Native Demo VideoLink to heading
The Complementarity Of React And Web ComponentsLink to heading
Immutable Data And ReactLink to heading
Beyond The DOM: How Netflix Plans To Enhance Your Television ExperienceLink to heading
Scalable Data VisualizationLink to heading
React RefractedLink to heading
Flux PanelLink to heading
Codecademy's Approach To Component CommunicationLink to heading
Static Typing With Flow And TypescriptLink to heading
Q&A With The TeamLink to heading

Document

React.js Conf 2015 Notes
Schedule, Videos
Wednesday
Keynote
Tom Occhino and Christopher Chedeau - Video
  • React History
  • React Native
  • React-like model for iOS and Android apps
  • Not shared code, shared mental model for writing apps
  • Application logic runs JS on background thread
  • Async APIs, batched updates (maps well to applying of diffs)
  • <div> → <View>, <span> → <Text>, <img> → <Image>, etc.
  • iOS and Android implementations
  • Still uses UINavigationController, etc. under the hood
  • Facebook Group app uses this
  • Demo tomorrow from Christopher
  • React Conf attendees will have access to the repo, full open source soon
Tweak your page in real time, without leaving the comfort of your editor
Brenton Simpson (prototyper at eBay, @appsforartists) - Video
  • Live reloading of CSS and components
  • Edit code, attached (mobile) devices auto-reload to pick up changes
  • Webpack as the module toolchain (alternative to browserify)
  • react-hot-loader extension for Webpack for replacing components on the fly
  • Ambidex: framework for abstracting away server-side vs. client-side rendering (“isomorphic” as the kids call it)
  • Declarative mechanism for indicating what data is needed for routes
  • Uses Reflux state to store fetched data, so that it can be reused on the client
Unlocking the structure of your React applications with the AST
Gurdas Nijor (FE engineer at OpenGov) - Video
  • Static analysis for UI code
  • Historically difficult:
  • DOM could be mutated everywhere
  • Templates are external
  • With React
  • Encapsulated within components
  • function of state and props only (no hidden runtime state)
  • Higher-level transformations
  • For example, instrumentation, component catalog, documentation generation
  • Instrumentation example:
  • Log all props changes
  • Create a ComponentWrapper that wraps each component
  • Uses componentWillReceiveProps to see when pros are received, emits change events
  • Rewrite all React.createElement calls to create a ComponentWrapper that wraps the actual element
  • Use esprima to generate an AST
  • Use escodegen to generate source from the AST
  • AST transformations
  • Many libraries, see github.com/estools
  • esprima's AST is just a bunch of JS object literals, can roll your own
  • http://felix-kling.de/esprima_ast_explorer/ for visualizing the esprima AST
  • Use Webpack loaders to run the transformations
  • Source → source filter
  • Can also add additional resources to the generated output
Data fetching for React applications at Facebook
Daniel Schafer (@dlschafer) and Jing Chen (@jingc) - Video
  • Problem
  • Tight coupling between server and views for data loading needs
  • Parents need to know what kind of data the child components will need (more coupling)
  • Child components did not have a mechanism for indicating what kind of data it needs (ideally statically)
  • Data specification mechanism
  • Complex shapes
  • Composable (so that parents can bundle up the specifications of their children)
  • GraphQL: query language for defining data requirements
  • Very granular, can request specific fields
  • Can represent one-to-many relationships
  • Not React-specific, also used on iOS
  • GraphQL in React
  • Add queries to statics
  • Use ES6 template stricts to embed GraphQL queries within component
  • Can reference queries from other components, so that we can compose
  • Generic/central store for storing all GraphQL response data
  • Relay: evolution of Flux
  • Framework that uses GraphQL in React
  • Can embed parameters in queries (e.g. for pagination)
  • Relay will cache data (if querying 15 items and 10 were previously fetched, only 5 will be fetched)
  • Query validation
  • Use queries to determine what components need to be updated when data changes
  • Framework handles optimistic updates, error handling, out of order 
  • Optimistic updates are maintained in a separate queue, overlaid on top of normal data. On error, remove from the overlay and re-notify all the components.
  • Also works with React Native
  • Want to open source, not doing it yet
  • Relay and GraphQL FAQ
Hallway ConversationS
  • Isaac Salier-Hellendag working on a reusable React component for doing text input with mentions, etc. The Facebook Groups app uses it.
  • UI code sharing between iOS and Android possible
  • But you may only want this for individual panes, use platform-specific containers to get a navigation stack
  • Mixins
  • Not feasible with ES6 class syntax
  • But you can just use subclass when using ES6, so ModelObjectListener and the like could be done as base classes
  • React.createClass will be staying around indefinitely, Facebook uses mixins internally heavily too
  • New model for refs (with lambda functions to stash a reference) has landed in master, will be in the 0.13 release
  • Relay open sourcing will happen eventually
  • There's already syntactic sugar for queries (via GraphQL), conceivably could do the same for CSS
  • React Native
  • Android
  • Uses JavaScriptCore (build their own from source)
  • Faster than V8, they can use all of the JIT layer, including the FTL
  • iOS
  • Uses JavaScriptCore
  • No JIT-ing
  • Experimented with JS code generation to avoid function call overhead
  • Tried using WKWebView, too many limitations, talking to Apple about them
  • People
  • Jordan Walke (React creator, currently working on React Native)
  • Paul O’Shannessy (React maintainer)
Communicating with channels
James Long (jlongster.com) - Slides, Video
  • Exploration of channels (communicating sequential processes) within React
  • Go-style channels
  • Channel fundamental operations
  • chan (create)
  • go
  • take
  • put
  • https://github.com/ubolonton/js-csp is a library for implementing channels in JS (using generators)
  • Firefox Dev Tools add-on to visualize data passing between channels
  • Unlike promises, channels are long-lived, can track values over time more easily
  • Coming soon:
  • “Promise channels” can implement promise-like behavior (repeated takes will return the same value)
  • Closing channels
  • Can compose with transducers (filtering and mapping of values)
  • Example: measuring mouse velocity
  • Can use closure to store state (previous mouse position), instead of embedding into the component
  • For an event handler that depends on previous state
  • Example: tooltip that shows up 500ms after hovering
  • on mouse enter:
  • start goroutine, take from either cancel channel or a 500ms timeout
  • if we took from the cancel channel, do nothing
  • otherwise show the tooltip
  • take from the cancel chanel (effectively blocks until mouseout)
  • hide the tooltip
  • on mouse leave:
  • put on cancel channel
react-router increases your productivity
Michael Jackson (@mjackson) and Ryan Florence - Video
  • https://github.com/rackt/react-router
  • History of the project
  • Nesting of routes
  • For a given /post/:id: URL, you might have:
  • edit
  • delete
  • etc.
  • Not necessarily tied to URL nesting
  • Wrapping (logged out vs. logged in views)
  • Transitions
  • Way to intercept moving from one route to another, and redirect/retry
  • For example, for preserving the continue URL while requiring authentication
  • Example: https://github.com/rackt/react-router/tree/master/examples/auth-flow
  • This uses global state (Login.attemptedTransition), unclear if it can be avoided (pass attempted transition to the Login as a prop?)
  • Can also use to implement onbeforeunload-type prompts (https://github.com/rackt/react-router/tree/master/examples/transitions)
The future of JavaScript layout systems Full-stack FLux
Pete Hunt (@floydophone) - Video
  • The future of JavaScript layout systems is...not GSS
  • Had problems
  • Constraint solver is not deterministic
  • Ended up writing raw CSS instead
  • Full-stack Flux (alternate topic)
  • Recap  of Flux architecture
  • Flux store is a wrapper for derived data
  • Given initial state and events/actions that followed, can answer questions
  • Server-side Flux
  • Use message queue to serve the role of the dispatcher (for durability, sharing, etc.)
  • Actions are put in the message queue
  • Stores get actions from message queue, process them, update their state
  • Can rebuild and migrate by replaying message queue
  • Subscribe to changes in stores, generate client-side actions
  • What didn't work/downsides:
  • Communication/dependencies between stores (no waitFor equivalent)
  • Strong consistency
  • Alternative:
  • Generate action after store is done processing action
  • Danger of loops
  • Need a direct-acyclic-graph (DAG) to avoid loops
  • Follow-on reading: https://thestrangeloop.com/sessions/turning-the-database-inside-out-with-apache-samza
Making your app fast with high-performance components
Jason Bonta (FE engineer on the Ads team at Facebook) - Video
  • Core component of the ads manager is the data table
  • Frozen row/column headers
  • Resizable columns
  • Dynamic row heights
  • Very large datasets
  • Pure rendering
  • Pairs well with immutable data structures
  • Problems with nesting, for example in a custom scrolling implementation
  • <OuterScroller scrollTop={props.offsetTop}>
        // InnerTable should use pure rendering, so that we don't re-render
        // when the scroll offset changes
        <InnerTable width="123" style="blue"/>
    </OuterScroller>
  • Problems with deep hierarchies
  • Need to pass data down through many levels
  • children are on the props object, array is re-created will, nullify PureRenderMixin
  • Can override shouldComponentUpdate to hardcode return false when it's guaranteed that nothing about the component will change (e.g. for layout primitives)
  • Separate data fetching (container) vs. rendering (passed in data as props). Containers don't have children, their render method just returns the rendering 
  • http://facebook.github.io/fixed-data-table/ was just open sourced, a high performance data table for large data sets
Format data and strings in any language with FormatJS and react-intl
Eric Ferraiuolo (@erifc, at Yahoo) - Video
  • ECMAScript 5.1 has i18n APIs
  • Intl.NumberFormat, Intl.DateTimeFormat, Intl.Collator
  • github.com/andyearnshaw/Intl.js is a polyfill
  • ICU has a message syntax that has standard representations of placeholders, pluralization, etc.
  • https://github.com/yahoo/react-intl is Yahoo's implementation for ICU-style localized strings
  • Has a mixin that makes it easy to pass down locale and other state (uses context)
  • http://formatjs.io/ is a lower-level library that the React library builds on top of
  • CLDR data is used to provide per-locale conventions (separator style, etc.)
Hype!
Ryan Florence - Demo Source, Video
  • Demos
  • Fast-updating data grid
  • https://github.com/rpflorence/react-magic-move
  • Automatically transitions elements between old/new positions
  • e.g. for re-sorting a buddy list based on presence state
  • https://github.com/rackt/react-a11y
  • monkey-patches React.createElement to add warning about non-acessible code
  • Portals
  • return null in render()
  • Add your own DOM nodes in componentDidMount instead.
  • Or you can use React.render to render an alternate component somewhere else in the DOM
  • https://github.com/rackt/react-modal
  • CSS Transitions on route changes
  • e.g. each month is a different route, have graphs that animate when the value for the month changes
  • Rely on fact that React reuses DOM nodes, just add CSS transitions
  • Isomorphic React Router demo
  • Including form submission
Thursday
Keynote - React NAtive DEmo Video
Christopher Chedeau (@vjeux)
  • Pillars
  • Touch handling
  • Native components
  • Style & Layout
  • Native components
  • <View> React component backed by RKVUIView native view
  • Props get mapped to UIView properties
  • Only the updating of UIView properties on the main thread, everything else is in the JS background thread
  • Developer experience
  • Can use Chrome Dev Tools (or the Safari one)
  • JavaScript can run on a separate device, communicates with the native container via Web Socket (could also server-side render components)
  • This is how the Dev Tools works, the JS runs in Chrome, thus you can use all of the tools, including the React Dev Tools
  • Live-reloading/watching of source changes
  • Red Screen of Death on JS exceptions, style pars errors, etc.
  • Styling
  • Not CSS
  • Inline styles, based on object literals embedded in the component
  • Recap of this presentation
  • For layout, existing iOS native approaches are either lots of math (manual layout) or math with syntactic sugar (auto-layout, especially when done via code)
  • iOS Auto-layout also cannot express some behaviors, like line breaks
  • CSS box model is good, but traditional positioning is painful
  • Flexbox is a much cleaner model
  • Re-implementation of (subset) Flexbox in JS
  • Compare computed layout with results of using Flexbox in the browser vs. the library
  • Using fuzzing to generate test cases for all supported properties
  • Text measurement is input to the layout algorithm, that needs to be done natively
  • So also transpiled it to Objective C and Java
  • Spun out to separate library, open-sourced at https://github.com/facebook/css-layout
  • Use ES6 string template literals to make it easy to embed CSS properties like rgba color values (including variables)
  • Conference attendees will be given access to the repo at 6pm
The complementarity of React and Web Components
Andrew Rota (@AndrewRota) - Video
  • Recap of Web Components
  • Pre-0.12 Couldn't use custom elements with React.render is because React didn't know it (it has a whitelist of DOM tag names)
  • After 0.12 all lower-cased or dashed tag names are treated as HTML
  • Can therefore use Web Components as leaf nodes in React render trees
  • Can't use React event handlers for custom events on components, will need to manually add listener in componentDidMount and unlisten in componentWillUnmount
  • If the component has side effects (e.g. <google-map> adds a <script> tag to the document), it'll have problems
  • Could theoretically use React within a web component, but that would make the component too heavy-weight
Immutable Data and React
Lee Byron (@leeb) -Video
  • http://facebook.github.io/immutable-js/
  • Implementation
  • Structural sharing: share as much as possible when making a new copy
  • Data structures need to be representable as DAGs
  • When modifying a node, can reuse children and nodes that are not on the path from the root to the node
  • Model arrays and key-value pairs as (index) tries
  • http://en.wikipedia.org/wiki/Hash_array_mapped_trie and http://hypirion.com/musings/understanding-persistent-vector-pt-1
  • For key-value pairs need to implement a hash function for the key
  • Constant factor slower, performance benefits are for doing from O(N) → O(log N)
  • Uses
  • Concurrency (lock-free), though not relevant to JS
  • Object.observe has problems (no batching, only observes immediate children, not more deeply nested elements)
  • dirty bits require you to couple UI framework with data model (to know when dirty fields can be cleared)
  • Memoization becomes easy (use reference comparison)
  • shouldComponentUpdate can use reference comparisons between old and new props (PureRenderMixin).
  • Flux: use immutable data structures (e.g. OrderedMap instead of object literals)
Beyond the DOM: How Netflix plans to enhance your television experience
Jafar Husain (Cross-team TL for UIs, on TC-39) - Video
  • Netflix needs:
  • Run on many devices
  • A/B testing (without app-store resubmission)
  • Three JS UIs (mobile, web, TV)
  • TV platform
  • 2010-2012: Embedded WebKit
  • DOM was too slow for low-end devices
  • New platform (Gibbon): JavaScriptCore and custom widget model
  • Absolute positioning only, one node type (widget), 25 style properties, async (bridge) API, explicit styles only
  • Can render to <canvas> (used for developing)
  • Mobile and web did React rewrites within the past year
  • Also use on the TV platform, for simplicity (and ability to do server-side generation of widget trees)
  • Needed access to internals, small fork initially (~67 lines)
  • Make Gibbon widgets look like a DOM element
  • After diffing, React emits HTML strings, needed to override this to emit list of JSON changes
  • ReactDOMComponent, ReactDOMOperation, createMarkupFromProperty
  • Switched instead to “spooning” React (using internal clases)
  • Similar approaches: react-art, react-pixi, react-three
  • With 0.13 components got lighter-weight, easier to create custom ones
Scalable Data Visualization
Zach Nation - Video
  • Visualization libraries handle both structuring of data for visualization (generating visual elements like graphs) and the rendering
  • Sample data set: Bitcoin transactions (21GB of data, 45 million transactions sequentially arranged)
  • Large data grid (one row per transaction, scrollable to arbitrary index)
  • Ran into browser limitations, could not have scrollable element of arbitrary height
  • Uses stateful server (since their product is single-user)
  • Can stream intermediate results to the client, but not too often, to not overwhelm the client
  • d3.js maps well to React: mostly pure functions and objects (except for selection and transitions, which expect to own the DOM)
React Refracted
David Nolen (engineer on ClojureScript, creator of Om, @swannodette) - Video
  • Unfamiliar != Complex
  • Big != Complex
  • Mutability should be an implementation detail (in Backbone, Angular, ember, mutability is the default)
  • Om design constraints
  • Immutable app state
  • Async rendering via requestAnimationFrame (mutations are batched)
  • Jump to any point in time with respect to application state
  • Modularity (due to lack of setState)
  • Feed current app state into root component
  • Changes to app state result in new instance, re-render everything
  • How to avoid passing down app state to all components in the tree (to avoid components reading app state they don't normally have access to)
  • “Cursor” used to provide a “windowed” piece of the app state to components (but still have reference to the app state, to update it)
  • Alternative to Flux to allow multiple components to depend on the same data without having to pass it down through all levels of the component hierarchy
  • “reference cursor” or “observable cursor”
  • Allows component to get a reference to a piece of the app state without getting it from props
  • First do normal rendering (top-down, based on app state/props)
  • Then do a second pass over all components that have a old of an observable cursor
  • If the value has changed (can still do reference comparisons here?) then do a forceUpdate on them
  • Example: why should the contents that are shown in a tab view be passed down as props to the parent?
  • Second pass over all components would benefit from having the component tree be available as a data structure to React clients
Flux Panel
Bill Fisher, Michael Ridgway (Yahoo!), Spike Brehm (Airbnb), Andres Suarez (SoundCloud), Jing Chen (Facebook), Ian Obermiller (Facebook), Kyle Davis (Facebook, Ads Power Editor) - Video
  • What does Relay mean for Flux?
  • Relay solves problems for big applications and teams
  • Power Editor
  • Data fetching within stores (106 stores total, ~64 stores that fetch data)
  • Data fetching triggered by store getters
  • Data fetches depend on existing data (e.g. for objects since the last fetch), so it needs data from the store
  • Two stores can respond to one action, both emit changes, controllers that listens to both would update twice
  • De-bounce calls based on dispatch loop
  • Normalize stores so that data is only stored in one (in an email client, have a Thread store and a Message store, even if a server request returns both threads and messages within them)
  • Isomorphic Flux
  • Dehydrate stores to serialize data that was fetched on the server and then use it to reuse it on the client
  • Two-pass rendering, first with loaded data from the server, second with client-side state, so that checksums match and no re-rendering is needed for server-rendered markup
  • SoundCloud uses Scala on top of Java 8
  • Using Browserify (to abstract away browser vs. server environment) can generate bundle of JS that can run inside of Nashorn (JS implementation on top of the JVM) to do server-side rendering
  • AirBnB
  • Migrating from Backbone
  • Wrapped Backbone models and collections in stores, to centralize loading
  • Optimistic updates and error updates
  • If you merge in optimistic update into object, then you lose state (and need an undo function)
  • Instead: separate map/overlay of optimistic updates, can remove on failure (and notify all listeners)
Codecademy's approach to component communication
Bonnie Eisenman (Codecademy, @brindelle) - Slides, Video
  • Component communication default strategy: callbacks everywhere (didn't consider Flux)
  • Needs:
  • Passing state changes to other parts of the tree
  • Communication targets change all the time
  • Approach: “Adapters”
  • Broadcasts notify adapters of something that changed
  • Adapter calls setState on components
  • Instance per major/top-level component
  • Server updates also notify adapters
Static typing with Flow and TypeScript
James Brantly (github.com/jbrantly) -  Code, Video
  • TypeScript
  • Getting TypeScript to understand JSX
  • There is a TypeScript fork that understands JSX, but it's a version behind
  • Wrap JSX in ES6 string literals, pre-process to turn into React.createElement calls (unclear why normal JSX compilation can't be done)
  • Need to teach TypeScript about CommonJS modules
  • Need to add definition files for what require('React') loads
  • Use ES6 class syntax to teach TypeScript that components are classes, so that it understands what this refers to, etc.
  • Flow
  • .flowconfig file with includes, etc.
  • Flow requires annotations at module boundaries (e.g. for render() return values)
  • Need to strip types as part of JSX compilation
Q&A with the team
Video
  • React in web workers: Currently React only one side, planning on React on the worker side too
  • iOS components is a React-like system that Facebook developed for the newsfeed (separate from React Native)
  • Relay runs JS on the server
  • Simple mode: determine what data needs to be fetched, fetch it, give it as part of the HTML response
  • Complex mode: simple + server-side rendering
  • Server-side rendering downsides:
  • Slower, due to auto-binding, initialization of state, other things that are not needed since it will be thrown away
  • Context
  • Warning in 0.13 if using parent vs. owner
  • Changes in reconciliation algorithm (shouldComponentUpdate, etc.)
  • Concept not going away
  • Origins in XHP (opaque data passed through templates, used to render profiles as other users by scoping some parts of the UI hierarchy to a different user)
  • Focus and selection are global states
  • Not meant to save you typing
  • Native components
  • Wrap vs. re-implement
  • E.g. tab bar in Facebook app is a re-implementation of UITabBar (for more flexibility)
  • Certain views only exist on one platform, re-implementation allows you to have a gradual migration path when porting to Android
  • Mixins
  • Pulled out of ES 6, On the table for ES 7
  • Add subscriptions to events/stores as first-class concept, to remove need for mixins for a lot of use-cases
  • Facebook packager
  • Machine learning to learn what packages need to be bundled together based on CDN requests
  • Also watch commit activity (e.g. packages that never change can be in the core/prelude package)
  • Optimizations for browser caches never affected metrics (hitting cold caches majority of time)
  • Data loading
  • In Relay can mark queries as deferred, so that they're not pre-fetched
  • RocksDB used for caching Relay data (in React Native)