content-driven apps with react
TRANSCRIPT
Content-Driven Apps with ReactCorsin Decurtins, Netcetera
2016-10-17 / Bern
BärnerJS
NotesContent-Driven Apps with ReactThis talk is a story about a family of projects or apps Actually not just individual apps, but app platforms Same team, same technology (roughly) Multiple projects, multiple apps, multiple customers But the same kind of app or actually app platform Mobile app, heavily content driven Customers are publishers, users are readers It all started with a proof-of-concept…
NotesProof of ConceptCustomer had a hybrid mobile app, Cordova and Angular (1) It was too slow for them, which resulted in a bad UX PoC done with React to see if we can improve the performance In particular the performance of the home page / start screen PoC showed, that we can Goal was a 50% improvement, he had up to 80% improvement This talk is about the app architecture that started with this PoC But it will be about anything but performance
Disclaimer
NotesDisclaimersI’m just the person giving the talk; other people did the actual work
If something is wrong or does not make sense, it’s probably me who messed it up
I’m familiar with the architecture, design and technologies If you have very detailed questions about the implementation, I will refer you to my colleagues
Ognen Ivanovski, Netcetera Principal Architect
Andon Sikavica, Netcetera Senior Software Engineer
NotesWho are you?Who is already familiar with… … React … React Native … Redux … Immutable Data, ImmutableJS … Pure Functions, Functional Programming
React
React Native
Redux
Functional Programming Pure Functions
Immutable Data immutable.js
Notes
Setting the Scene
Web-Based Hybrid Mobile Apps
NotesWeb-Based Hybrid Mobile AppsMobile apps for smartphones and tablets Hybrid, i.e. one code base for all the platforms Based on web technologies, i.e. HTML, Javascript, CSS and JSON
Based on web tooling (debuggers, CSS, NPM, gulp, ECMAScript, …)
Cordova is the most common runtime platform for creating packaged apps that can be delivered to the app store
Web-Based* Hybrid Mobile** Apps***
NotesWeb-Based Hybrid Mobile AppsWeb based can be interpreted loosely Instead of HTML, other markup is possible, including markup for native components
Also not restricted to mobile apps, you can build other apps as well
Not even restricted to apps, can be used for “websites”
Content-Driven Apps
NotesContent-Driven AppsMobile apps that are mostly used to consume and browse through content
News apps for example Get content from a server Content from the server determines the screens, the interaction and the navigation
The browser is probably the ultimate example
NotesContent-Driven AppsWe started out with news apps for publishers But there are a lot of other examples
Notes
High-Level Architecture
App
Cordova
app.js
Libraries
CMS
DAM
Ads
IAM
EntitlementPlatform
SkinningConfigAPI
Cache
Widgets
MetricsAnalytics
NotesArchitectureClient App, JS, packaged with Cordova Libraries, Widgets, Generic Platform Code These are part of the platform and the same for all the apps of the platform
App-specific configuration and skinning Content is retrieved from the server-side through an API Abstracts various backend systems such as the CMS, DAM, … API might have a server-side cache
NotesChallengesApp Platform vs. just an app Reuse of code, platform, configuration, customising, skinning
API Evolution Apps are deployed, no instant updates
Performance, User Experience (UX) Time-To-Market and Price
Notes
Design, Patterns, Concepts, Technologies, …
React
NotesReact ComponentsTree of React Components JS objects, can be as simple as one function Every component has a render() function Can be static (children are hard-coded in the parent) or dynamic (children are added based on data of the parent-components)
NotesStateEvery React component can have an inner state State is optional State must only be manipulated through an defined interface Gives React a chance to know when the state has changed and the component needs to be re-rendered
NotesAttributesIn addition to the internal state, React components can also receive data from parent components through attributes
Can be used for rendering Can be used for initialising state
const CommentForm = React.createClass({
getInitialState: () => { return {author: '', text: ''}; },
handleAuthorChange: (e) => { this.setState({author: e.target.value}); }, handleTextChange: (e) => { this.setState({text: e.target.value}); }, handleSubmit: (e) => { e.preventDefault(); // do something },
... });
const CommentForm = React.createClass({ ... render: function() { return ( <form className="commentForm" onSubmit={this.handleSubmit}> <input type=“text" placeholder="Your name" value={this.state.author} onChange={this.handleAuthorChange} /> <input type=“text" placeholder="Say something..." value={this.state.text} onChange={this.handleTextChange} /> <input type="submit" value="Post" /> </form> ); } });
React Components Virtual DOM DOM
NotesReact RenderingReact Components have a render() function that produces HTML
Actually it produces a tree of objects that correspond to HTML
The React Components are rendered into a Virtual DOM first The Virtual DOM is then rendered into the actual DOM
NotesReact RenderingPure Functions for the transformations (aka rendering) Events flow in reverse to the transformation flow React Optimisations Propagate diffs rather than new trees Lots and lots of checks for changes for trees and subtrees Modify data (state or attributes) only through well-defined interfaces
Immutable Data
React Components Virtual DOM DOM
NotesImmutable DataData cannot be changed Every change results in a new copy of a data structure Optimisation: Data structure can contain references to data of other data structures (since they can never change)
Equality check with immutable data becomes very efficient Check if the reference is the same React change check (shouldComponentUpdate) can be implemented very efficiently
Redux
Dan Abramov Hot Reloading with Time Travel
https://youtu.be/xsSnOQynTHs
reducerreducerreducerreducer
const newsReducer = (state = {}, action) => { if (action.type === ‘NEWS_UPDATE’) { return Object.assign(
{}, state, {stories: action.stories} ); } return state; };
NotesReduxApplication state consists of one state object React components do not have a state anymore Application state is passed into React as an attribute Reducers handle all the events and transfer the app from one state into another
Creation of the React Component tree is a pure function Rendering of the React Component tree is a pure function Reducers are pure functions
reducerreducerreducerreducer reducerreducerreducerreducer reducerreducerreducerreducer
Notes
Loading Content from the Server (or from a local cache)
Content API{ "kind": ["image", "diagram"], "imageUrl": “http://example.com/diagram.png" "caption": “Super Cool Diagram" }
NotesContent APIObjects in the content tree are called elements Kind describes the (hierarchical) type of an element Additional type-specific attributes are part of the element Above example is the element description for an image Can for example be a nice diagram Customer wants to add support for an interactive diagram (zoom and
pan, play around with values, …) Create a new element, support on the CMS and in the app Create the new element as an extension/refinement of the old one
Content API{ "kind": [“image”, “diagram”, “interactive”], “dataUrl”: “https://example.com/data/diagram.json”, "imageUrl": “https://example.com/diagram.png" "caption": “Super Cool Diagram" }
NotesContent APINew sub-type ‘interactive’ Data URL for loading the data for the diagram But the component is also an [‘image’, ‘diagram’] with ‘imageUrl’ and ‘caption’
If a client does not support ‘interactive’ yet, the component can also just be rendered as an image/diagram
reducerreducerreducerreducer reducerreducerreducerreducer reducerreducerreducerreducer
NotesLoading Content (Simplified)Reducer triggers a request for loading content Technically, this is a side-effect and the reducer is not a pure function
anymore Side-Effect is on an external system, asynchronous handling When the data arrives, that triggers a new event for the reducers Data passes through a series of transformers (“pure” functions) that
transform the received data into data that can be incorporated into the application state … as well as side-effect events for loading additional data
NotesReact / Redux / ImmutablePure functions everywhere Logically, everything is immutable and pure functions Physically, React makes optimisations
NotesInteresting PropertiesSerialisable application state Testing Time-Machine Performance Code Quality Code Reuse
Notes
Excursions
Web Applications
NotesWeb ApplicationsNothing mentioned above is specific to mobile apps You can also use the architecture for “normal” web applications
Desktop web applications, mobile apps, responsive apps, …
React Native
React
React DOM React Native
NotesReact NativeRelatively recent extension of the React Framework Everything remains the same, React Components and if you use it Redux, …
Instead of rendering HTML objects (using ReactDOM and JSX), you render markup for Native Components
Native Runtime, Native Apps, Javascript as Scripting Engine Native Performance, but still Hybrid
Server-Side Rendering
React Components Virtual DOM HTML Document
HTML
NotesServer-Side RenderingReact Components can be rendered into a string HTML code only HTML code is dead, i.e. it does not contain any active parts (Javascript)
Can be used for pre-rendering on the server-side Make content available for search engine and other non-browser clients
Testing
Notes
Summary
Technologies and Concepts
reducerreducerreducerreducer reducerreducerreducerreducer reducerreducerreducerreducer
NotesTechnologies and ConceptsTechnology choices have a big impact on design and fundamental
concepts React, Redux and other members of this family have a clear heritage of
functional programming This has a learning curve It takes some time until you “get it” And then it takes some more time until you really “get it” Concepts are very different from what our developers were used too There was a learning curve until it really clicks
NotesTechnologies and ConceptsSome things seem unnecessarily complicated and limiting Most of the time, they are actually not They seem complicated, because they are unfamiliar and you have not started to think in a React/Redux/Functional way
Code Base in the end is much more fragmented More small granular components than with other core technologies Complexity is still smaller though, because the small components follow very clear, simple and orthogonal concepts
NotesTechnologies and ConceptsConcepts (and technologies) allow for really cool and helpful things
Testing, Time-Machine, React DevTools Clean, simple, well-abstracted and clean code Reusable and extensible code Content API allows for very powerful customisation and extension … of existing apps and use cases
Girders Elements https://github.com/netceteragroup/girders-elements
NotesGirders ElementsWe had the chance to go through multiple iterations with the described
architecture Both with React DOM and React Native One of the current customers gave us the chance to extract the core
framework of the architecture and open-source it This is called Girders Elements It is currently being developed … in parallel with the platform and some
apps for the mentioned customer Not production-ready yet
NotesGirders ElementsReact, React DOM or React Native, Redux and other core libraries
Framework, Wiring, Configuration, UI Widgets (Customisable, Skinnable)
NotesGirders ElementsIf you are very familiar with the concepts and libraries that I mentioned -> use it and contribute to it
If you are not familiar with the concepts and libraries yet -> wait for a few months
Girders Elements is still under development Documentation is not there yet But we will get there eventually
Corsin Decurtins, Netcetera Chief Technology Officer
[email protected] @corsin
reducerreducerreducerreducer reducerreducerreducerreducer reducerreducerreducerreducer
Content-Driven Apps with ReactCorsin Decurtins, Netcetera
2016-10-17 / Bern
BärnerJS