The Case for React.js and ClojureScript
Upcoming SlideShare
Loading in...5
×
 

The Case for React.js and ClojureScript

on

  • 1,184 views

Sonian Tech Talk presentation given on may 2, 2014.

Sonian Tech Talk presentation given on may 2, 2014.

http://murilopereira.com/the-case-for-reactjs-and-clojurescript/

Statistics

Views

Total Views
1,184
Slideshare-icon Views on SlideShare
1,183
Embed Views
1

Actions

Likes
2
Downloads
14
Comments
0

1 Embed 1

http://www.slideee.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    The Case for React.js and ClojureScript The Case for React.js and ClojureScript Presentation Transcript

    • The Case for React.js and ClojureScript Murilo Pereira @mpereira May2, 2014
    • Problem
    • Building UIs is difficult.
    • Modern Web UIs visualrepresentationsofdatachangingovertime respondtoasynchronoususerevents transitionboththeunderlyingdataanditselftonew states
    • "Data changing over time is the root of all evil."
    • Incidental Complexity JavaScriptisn't DOM is stateful reactive
    • What if the JavaScript DOM API was reactive?
    • functiontweetScore(tweet){ return(tweet.favorites_count+tweet.retweets_count); } functioncompareTweetsByScore(a,b){ return(tweetScore(b)-tweetScore(a)); } functionrenderApplication(tweets){ return(document.dom.ul( {class:'tweets'}, tweets .sort(compareTweetsByScore) .slice(0,5) .map(function(tweet){ return(document.dom.li({class:'tweet'},tweet.text); }) )); } vartweets=fetchTweets({username:'mpereira'},{limit:20}); document.dom.render(renderApplication(tweets),document.body);
    • Possible solution: Data binding
    • Data Binding Observables Computed properties Backbone, Ember, Meteor, etal.
    • Contemporary data binding is not simple.
    • Simple Notto be mistaken for "easy" Easiness = Familiarity(subjective) Simplicity= "Does/is one thing"(objective)
    • Data Binding Application logic entangled with observables Forces us to compose our programs with framework constructs instead of language constructs (functions and data structures)
    • "How often are you fighting the framework?"
    • Dirty-checking (Angular) Also susceptible to the problems of databinding.
    • https://docs.angularjs.org/guide/concepts
    • Complex
    • Even with shortcomings it's still possible to build complex, modern UIs using contemporary MVC frameworks.
    • "We can create precisely the same programs we're creating right now with drastically simpler tools." Rich Hickey
    • A different solution to the same problem.
    • React.js
    • React.js Libraryfor creatingUIs Renders the DOM and responds to user events Can be thoughtof as the Vin MVC
    • Remember our utopic example a few slides back?
    • functiontweetScore(tweet){ return(tweet.favorites_count+tweet.retweets_count); } functioncompareTweetsByScore(a,b){ return(tweetScore(b)-tweetScore(a)); } functionrenderApplication(tweets){ return(document.dom.ul( {class:'tweets'}, tweets .sort(compareTweetsByScore) .slice(0,5) .map(function(tweet){ return(document.dom.li({class:'tweet'},tweet.text); }) )); } vartweets=fetchTweets({username:'mpereira'},{limit:20}); document.dom.render(renderApplication(tweets),document.body);
    • It's actually valid React.js code
    • functiontweetScore(tweet){ return(tweet.favorites_count+tweet.retweets_count); } functioncompareTweetsByScore(a,b){ return(tweetScore(b)-tweetScore(a)); } functionrenderApplication(tweets){ return(React.DOM.ul( {className:'tweets'}, tweets .sort(compareTweetsByScore) .slice(0,5) .map(function(tweet){ return(React.DOM.li({className:'tweet'},tweet.text); }) )); } vartweets=fetchTweets({username:'mpereira'},{limit:20}); React.renderComponent(renderApplication(tweets),document.body);
    • React gives us a minimally leaky abstraction for a reactive JavaScript/DOM environment.
    • Data Component DOM
    • Model View DOM
    • M3 V2 DOM M2 M4 M5M1 V1 V3
    • Data C3 DOM C4C2 C5C1
    • Components
    • Components Idempotent functions that describe your UI at any point in time.
    • component(data) = VDOM
    • component(data_1) = VDOM_1 *user inputchanges datafrom data_1 to data_2* component(data_2) = VDOM_2 diffVDOMs(VDOM_1, VDOM_2) = diff DOMOperations(diff) = operations applyDOMOperations(operations, document.body)
    • Best part? You don't even have to worry about this. Just build components.
    • Every place data is displayed is guaranteed to be up-to-date.  No need for KVO or marking HTML templates with framework directives.
    • Frees the programmer from doing manual, explicit DOM operations.
    • But what about the performance? Isn't diffing VDOMs slow? Why have VDOMs if the browser already has a DOM?
    • The DOM is slow.
    • The DOM is slow Queryingmayrequire tree traversal Mutations trigger viewportreflows, relayouts, repaints (CSS engine, etc.) Can also invalidate caches, requiringthe entire DOM to be reconstructed on the viewport
    • Having in-memory representations of the DOM allows React to have extremely fast UIs.
    • Virtual DOM (VDOM) Allows for components to have adeclarative API Performs the minimum amountof actualDOM operations through computingdiffs Handles DOM operations for you
    • "Performance isn't the [main] goal of the VDOM, but if you're worried with performance, most workloads are as fast or faster [than the MVC alternatives] out of the box." Pete Hunt
    • Components
    • Components allow you to express your program in the language of your problem domain. Rather than on the language of a particular framework.
    • Bill O'Reilly Tide comesin,tide goesout. You can'texplain that! Top Tweets Justhad #breakfast. @troll yes,definitelyplan on that. pic.twitter.com/asd23 #selfie #instagram Good# morning.
    • Bill O'Reilly Top Tweets Tide comesin,tide goesout. You can'texplain that!#tides Justhad #breakfast. @troll yes,definitelyplan on that. pic.twitter.com/asd23 #selfie #instagram Good# morning. Header Profile Tweets Top Tweets
    • varProfile=React.createClass({ render:function(){ return(React.DOM.div(null,[ React.DOM.img(null,this.props.user.image), React.DOM.p(null,this.props.user.name) ]); } }); varTweets=React.createClass({ render:function(){ return(React.DOM.ul(null,this.props.tweets.map(function(tweet){ return(React.DOM.li(null,tweet.text)); }); } }); varTopTweets=React.createClass({ render:function(){ return(React.DOM.div(null,[ React.DOM.h1(null,'TopTweets'), Profile({user:this.props.user}), Tweets({tweets:this.props.user.tweets}) ]); } }); React.renderComponent(TopTweets({user:user}),document.body);
    • varProfile=React.createClass({ render:function(){ return( <div> <imghref={this.props.user.image}/> <p>{this.props.user.name}</p> </div> ); } }); varTweets=React.createClass({ render:function(){ return( <ul> {this.props.tweets.map(function(tweet){ return(<li>tweet.text</li>); })}; </ul> ); } }); varTopTweets=React.createClass({ render:function(){ return( <div> <h1>TopTweets</h1> <Profileuser={this.props.user}/> <Tweetstweets={this.props.user.tweets}/> </div> ); }
    • TopTweets(data) = Header() + Profile(data_1) + Tweets(data_2)
    • Components are reusable and composable declarative representations of your UI.
    • Collateral Benefits
    • Collateral Benefits Render the application on the server (node.js, Java8's Nashhorn, etc.) UI testabilityfor free No templates!
    • React.js takeaways Declarative, fastUIs Express your programs in the language of your problem domain
    • ClojureScript
    • Problem JavaScript sucks We needJavaScript
    • JavaScript sucks No integers No module system Verbose syntax Confusing, inconsistentequalityoperators Confusing, inconsistentautomatic operator conversions Lack of block scope Non-uniform iterators Globalvariables bydefault NaN this No macros (yet...) etc.
    • We Need JavaScript Runtime is everywhere Runtime is improving(Web Sockets, geo-location, FS API, RAF, push notifications, WebRTC, WebGL, SVG, Canvas, Web Workers, IndexedDB, etc.)
    • Build better languages on top of JavaScript.
    • Compilers! Lots of them alreadyexist Onlyafew bringsignificantimprovements Popular ones CoffeeScript: mostlysyntax sugar TypeScript: typed supersetof JavaScript. Brings type checking, compile time errors
    • ClojureScript
    • ClojureScript is a Clojure compiler that targets JavaScript.
    • Why ClojureScript? Why Clojure? Why LISP?
    • Clojure is just a better language.
    • Numberofdays spentdesigning the language v1 JavaScript Clojure
    • ClojureScript LISP STM Runtime polymorphism The REPL Functionalprogramming Immutable datastructures Uniform API over immutable datastructures Macros Lazysequences Destructuring State VS Identity etc.
    • core.async (go(try (let[tweets (<?(get-tweets-for"swannodette")) first-url(<?(expand-url(first(parse-urlstweets)))) response (<?(http-getfirst-url))] (.js/console(log"Mostrecentlinktext:"response))) (catchjs/Errore (.js/console(error"Errorwiththetwitterverse:"e))))) Asynchronous Error Handling
    • The possibility of having access to the power of Clojure in the browser is immensely valuable.
    • Value To programmers, who willbe able to build better programs, with less bugs, faster. To the people and companies who willbenefitfrom those programs.
    • The developer experience has improved significantly.
    • Developer Experience Source maps Easilyreproducible tutorials Browser-connected in-editor REPLs Fastcompilation cycles Compatible libraries
    • Recommend you to check it out (butyou probablyhave, already)
    • Om
    • ClojureScript interface to React.
    • "Because of immutable data Om can deliver even better performance than React out of the box." David Nolen
    • 30-40X faster than JS MVCs nothing to do with ClojureScript. Ditch stateful objects, ditch events. Be declarative. Immutability. That's it. 5:39 AM - 15 Dec 2013 David Nolen @swannodette Follow 41 RETWEETS 39 FAVORITES
    • ???
    • ClojureScript Compiled, slower than hand-written JavaScript Uses immutable datastructures, slower than JavaScriptdata structures And yet Om's performance beats that of most JavaScript MVC frameworks
    • "Ideas have fundamental performance properties." Pete Hunt
    • Immutable data structures make React's diffing algorithm really smart.
    •  And more...
    • Takeaways
    • "Ideas have fundamental performance properties."
    • "Don't trade simplicity for familiarity."
    • And  .give it five minutes
    • Thanks!@mpereira
    • Learn React.js Why? Be Predictable, NotCorrect React: RethinkingBestPractices WhyReact? How GettingStarted Introduction to React.js Tutorial
    • Learn ClojureScript Why? ClojureScriptRationale The Future of JavaScriptMVC Frameworks Clojure Rationale WhyClojure? Beatingthe Averages How ClojureScript101 Translations from JavaScript LightTable ClojureScriptTutorial Om Tutorial