Community Round-up #10

November 6, 2013 by Vjeux


This is the 10th round-up already and React has come quite far since it was open sourced. Almost all new web projects at Khan Academy, Facebook, and Instagram are being developed using React. React has been deployed in a variety of contexts: a Chrome extension, a Windows 8 application, mobile websites, and desktop websites supporting Internet Explorer 8! Language-wise, React is not only being used within JavaScript but also CoffeeScript and ClojureScript.

The best part is that no drastic changes have been required to support all those use cases. Most of the efforts were targeted at polishing edge cases, performance improvements, and documentation.

Khan Academy - Officially moving to React #

Joel Burget announced at Hack Reactor that new front-end code at Khan Academy should be written in React!

How did we get the rest of the team to adopt React? Using interns as an attack vector! Most full-time devs had already been working on their existing projects for a while and weren't looking to try something new at the time, but our class of summer interns was just arriving. For whatever reason, a lot of them decided to try React for their projects. Then mentors became exposed through code reviews or otherwise touching the new code. In this way React knowledge diffused to almost the whole team over the summer.

Since the first React checkin on June 5, we've somehow managed to accumulate 23500 lines of jsx (React-flavored js) code. Which is terrifying in a way - that's a lot of code - but also really exciting that it was picked up so quickly.

We held three meetings about how we should proceed with React. At the first two we decided to continue experimenting with React and deferred a final decision on whether to adopt it. At the third we adopted the policy that new code should be written in React.

I'm excited that we were able to start nudging code quality forward. However, we still have a lot of work to do! One of the selling points of this transition is adopting a uniform frontend style. We're trying to upgrade all the code from (really old) pure jQuery and (regular old) Backbone views / Handlebars to shiny React. At the moment all we've done is introduce more fragmentation. We won't be gratuitously updating working code (if it ain't broke, don't fix it), but are seeking out parts of the codebase where we can shoot two birds with one stone by rewriting in React while fixing bugs or adding functionality.

Read the full article

React: Rethinking best practices #

Pete Hunt's talk at JSConf EU 2013 is now available in video.

Server-side React with PHP #

Stoyan Stefanov's series of articles on React has two new entries on how to execute React on the server to generate the initial page load.

This post is an initial hack to have React components render server-side in PHP.

  • Problem: Build web UIs
  • Solution: React
  • Problem: UI built in JS is anti-SEO (assuming search engines are still noscript) and bad for perceived performance (blank page till JS arrives)
  • Solution: React page to render the first view
  • Problem: Can't host node.js apps / I have tons of PHP code
  • Solution: Use PHP then!

Read part 1 ...

Read part 2 ...

Rendered markup on the server:

TodoMVC Benchmarks #

Webkit has a TodoMVC Benchmark that compares different frameworks. They recently included React and here are the results (average of 10 runs in Chrome 30):

  • AngularJS: 4043ms
  • AngularJSPerf: 3227ms
  • BackboneJS: 1874ms
  • EmberJS: 6822ms
  • jQuery: 14628ms
  • React: 2864ms
  • VanillaJS: 5567ms

Try it yourself!

Please don't take those numbers too seriously, they only reflect one very specific use case and are testing code that wasn't written with performance in mind.

Even though React scores as one of the fastest frameworks in the benchmark, the React code is simple and idiomatic. The only performance tweak used is the following function:

/**
 * This is a completely optional performance enhancement that you can implement
 * on any React component. If you were to delete this method the app would still
 * work correctly (and still be very performant!), we just use it as an example
 * of how little code it takes to get an order of magnitude performance improvement.
 */
shouldComponentUpdate: function (nextProps, nextState) {
  return (
    nextProps.todo.id !== this.props.todo.id ||
    nextProps.todo !== this.props.todo ||
    nextProps.editing !== this.props.editing ||
    nextState.editText !== this.state.editText
  );
},

By default, React "re-renders" all the components when anything changes. This is usually fast enough that you don't need to care. However, you can provide a function that can tell whether there will be any change based on the previous and next states and props. If it is faster than re-rendering the component, then you get a performance improvement.

The fact that you can control when components are rendered is a very important characteristic of React as it gives you control over its performance. We are going to talk more about performance in the future, stay tuned.

Guess the filter #

Connor McSheffrey implemented a small game using React. The goal is to guess which filter has been used to create the Instagram photo.

React vs FruitMachine #

Andrew Betts, director of the Financial Times Labs, posted an article comparing FruitMachine and React.

Eerily similar, no? Maybe Facebook was inspired by Fruit Machine (after all, we got there first), but more likely, it just shows that this is a pretty decent way to solve the problem, and great minds think alike. We're graduating to a third phase in the evolution of web best practice - from intermingling of markup, style and behaviour, through a phase in which those concerns became ever more separated and encapsulated, and finally to a model where we can do that separation at a component level. Developments like Web Components show the direction the web community is moving, and frameworks like React and Fruit Machine are in fact not a lot more than polyfills for that promised behaviour to come.

Read the full article...

Even though we weren't inspired by FruitMachine (React has been used in production since before FruitMachine was open sourced), it's great to see similar technologies emerging and becoming popular.

React Brunch #

Matthew McCray implemented react-brunch, a JSX compilation step for Brunch.

Adds React support to brunch by automatically compiling *.jsx files.

You can configure react-brunch to automatically insert a react header (/** @jsx React.DOM */) into all *.jsx files. Disabled by default.

Install the plugin via npm with npm install --save react-brunch.

Read more...

Random Tweet #

I'm going to start adding a tweet at the end of each round-up. We'll start with this one:

React v0.5.1

October 29, 2013 by Paul O’Shannessy


This release focuses on fixing some small bugs that have been uncovered over the past two weeks. I would like to thank everybody involved, specifically members of the community who fixed half of the issues found. Thanks to Ben Alpert, Andrey Popp, and Laurence Rowe for their contributions!

Changelog #

React #

  • Fixed bug with <input type="range"> and selection events.
  • Fixed bug with selection and focus.
  • Made it possible to unmount components from the document root.
  • Fixed bug for disabled attribute handling on non-<input> elements.

React with Addons #

  • Fixed bug with transition and animation event detection.

React v0.5

October 16, 2013 by Paul O’Shannessy


This release is the result of several months of hard work from members of the team and the community. While there are no groundbreaking changes in core, we've worked hard to improve performance and memory usage. We've also worked hard to make sure we are being consistent in our usage of DOM properties.

The biggest change you'll notice as a developer is that we no longer support class in JSX as a way to provide CSS classes. Since this prop was being converted to className at the transform step, it caused some confusion when trying to access it in composite components. As a result we decided to make our DOM properties mirror their counterparts in the JS DOM API. There are a few exceptions where we deviate slightly in an attempt to be consistent internally.

The other major change in v0.5 is that we've added an additional build - react-with-addons - which adds support for some extras that we've been working on including animations and two-way binding. Read more about these addons in the docs.

Thanks to Our Community #

We added 22 new people to the list of authors since we launched React v0.4.1 nearly 3 months ago. With a total of 48 names in our AUTHORS file, that means we've nearly doubled the number of contributors in that time period. We've seen the number of people contributing to discussion on IRC, mailing lists, Stack Overflow, and GitHub continue rising. We've also had people tell us about talks they've given in their local community about React.

It's been awesome to see the things that people are building with React, and we can't wait to see what you come up with next!

Changelog #

React #

  • Memory usage improvements - reduced allocations in core which will help with GC pauses
  • Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
  • Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
  • Support for Selection events.
  • Support for Composition events.
  • Support for additional DOM properties (charSet, content, form, httpEquiv, rowSpan, autoCapitalize).
  • Support for additional SVG properties (rx, ry).
  • Support for using getInitialState and getDefaultProps in mixins.
  • Support mounting into iframes.
  • Bug fixes for controlled form components.
  • Bug fixes for SVG element creation.
  • Added React.version.
  • Added React.isValidClass - Used to determine if a value is a valid component constructor.
  • Removed React.autoBind - This was deprecated in v0.4 and now properly removed.
  • Renamed React.unmountAndReleaseReactRootNode to React.unmountComponentAtNode.
  • Began laying down work for refined performance analysis.
  • Better support for server-side rendering - react-page has helped improve the stability for server-side rendering.
  • Made it possible to use React in environments enforcing a strict Content Security Policy. This also makes it possible to use React to build Chrome extensions.

React with Addons (New!) #

  • Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. Read more in the docs.

JSX #

  • No longer transform class to className as part of the transform! This is a breaking change - if you were using class, you must change this to className or your components will be visually broken.
  • Added warnings to the in-browser transformer to make it clear it is not intended for production use.
  • Improved compatibility for Windows
  • Improved support for maintaining line numbers when transforming.

Community Round-up #9

October 3, 2013 by Vjeux


We organized a React hackathon last week-end in the Facebook Seattle office. 50 people, grouped into 15 teams, came to hack for a day on React. It was a lot of fun and we'll probably organize more in the future.

React Hackathon Winner #

Alex Swan implemented Qu.izti.me, a multi-player quiz game. It is real-time via Web Socket and mobile friendly.

The game itself is pretty simple. People join the "room" by going to http://qu.izti.me on their device. Large displays will show a leaderboard along with the game, and small displays (such as phones) will act as personal gamepads. Users will see questions and a choice of answers. The faster you answer, the more points you earn.

In my opinion, Socket.io and React go together like chocolate and peanut butter. The page was always an accurate representation of the game object.

Read More...

JSConf EU Talk: Rethinking Best Practices #

Pete Hunt presented React at JSConf EU. He covers three controversial design decisions of React:

  1. Build components, not templates
  2. Re-render the whole app on every update
  3. Virtual DOM

The video will be available soon on the JSConf EU website, but in the meantime, here are Pete's slides:

Pump - Clojure bindings for React #

Alexander Solovyov has been working on React bindings for ClojureScript. This is really exciting as it is using "native" ClojureScript data structures.

(ns your.app
  (:require-macros [pump.def-macros :refer [defr]])
  (:require [pump.core]))

(defr Component
  :get-initial-state #(identity {:some-value ""})

  [component props state]

  [:div {:class-name "test"} "hello"])

Check it out on GitHub...

JSXHint #

Todd Kennedy working at Condé Nast implemented a wrapper on-top of JSHint that first converts JSX files to JS.

A wrapper around JSHint to allow linting of files containg JSX syntax. Accepts glob patterns. Respects your local .jshintrc file and .gitignore to filter your glob patterns.

npm install -g jsxhint

Check it out on GitHub...

Turbo React #

Ross Allen working at Mesosphere combined Turbolinks, a library used by Ruby on Rails to speed up page transition, and React.

"Re-request this page" is just a link to the current page. When you click it, Turbolinks intercepts the GET request and fetchs the full page via XHR.

The panel is rendered with a random panel- class on each request, and the progress bar gets a random widthX class.

With Turbolinks alone, the entire would be replaced, and transitions would not happen. In this little demo though, React adds and removes classes and text, and the attribute changes are animated with CSS transitions. The DOM is otherwise left intact.

Check out the demo...

Reactive Table #

Stoyan Stefanov continues his series of blog posts about React. This one is an introduction tutorial on rendering a simple table with React.

React is all about components. So let's build one.

Let's call it Table (to avoid any confusion what the component is about).

var Table = React.createClass({
  /*stuff goeth here*/
});

You see that React components are defined using a regular JS object. Some properties and methods of the object such as render() have special meanings, the rest is upforgrabs.

Read the full article...

Community Round-up #8

September 24, 2013 by Vjeux


A lot has happened in the month since our last update. Here are some of the more interesting things we've found. But first, we have a couple updates before we share links.

First, we are organizing a React Hackathon in Facebook's Seattle office on Saturday September 28. If you want to hack on React, meet some of the team or win some prizes, feel free to join us!

We've also reached a point where there are too many questions for us to handle directly. We're encouraging people to ask questions on StackOverflow using the tag [reactjs]. Many members of the team and community have subscribed to the tag, so feel free to ask questions there. We think these will be more discoverable than Google Groups archives or IRC logs.

Javascript Jabber #

Pete Hunt and Jordan Walke were interviewed on Javascript Jabber for an hour. They go over many aspects of React such as 60 FPS, Data binding, Performance, Diffing Algorithm, DOM Manipulation, Node.js support, server-side rendering, JSX, requestAnimationFrame and the community. This is a gold mine of information about React.

PETE: So React was designed all around that. Conceptually, how you build a React app is that every time your data changes, it's like hitting the refresh button in a server-rendered app. What we do is we conceptually throw out all of the markup and event handlers that you've registered and we reset the whole page and then we redraw the entire page. If you're writing a server-rendered app, handling updates is really easy because you hit the refresh button and you're pretty much guaranteed to get what you expect.

MERRICK: That's true. You don't get into these odd states.

PETE: Exactly, exactly. In order to implement that, we communicate it as a fake DOM. What we'll do is rather than throw out the actual browser html and event handlers, we have an internal representation of what the page looks like and then we generate a brand new representation of what we want the page to look like. Then we perform this really, really fast diffing algorithm between those two page representations, DOM representations. Then React will compute the minimum set of DOM mutations it needs to make to bring the page up to date.

Then to finally get to answer your question, that set of DOM mutations then goes into a queue and we can plug in arbitrary flushing strategies for that. For example, when we originally launched React in open source, every setState would immediately trigger a flush to the DOM. That wasn't part of the contract of setState, but that was just our strategy and it worked pretty well. Then this totally awesome open source contributor Ben Alpert at Khan Academy built a new batching strategy which would basically queue up every single DOM update and state change that happened within an event tick and would execute them in bulk at the end of the event tick.

Read the full conversation ...

JSXTransformer Trick #

While this is not going to work for all the attributes since they are camelCased in React, this is a pretty cool trick.

Remarkable React #

Stoyan Stefanov gave a talk at BrazilJS about React and wrote an article with the content of the presentation. He goes through the difficulties of writing active apps using the DOM API and shows how React handles it.

So how does exactly React deal with it internally? Two crazy ideas - virtual DOM and synthetic events.

You define you components in React. It builds a virtual DOM in JavaScript land which is way more efficient. Then it updates the DOM. (And "virtual DOM" is a very big name for what is simply a JavaScript object with nested key-value pairs)

Data changes. React computes a diff (in JavaScript land, which is, of course, much more efficient) and updates the single table cell that needs to change. React replicates the state of the virtual DOM into the actual DOM only when and where it's necessary. And does it all at once, in most cases in a single tick of the requestAnimationFrame().

What about event handlers? They are synthetic. React uses event delegation to listen way at the top of the React tree. So removing a node in the virtual DOM has no effect on the event handling.

The events are automatically cross-browser (they are React events). They are also much closer to W3C than any browser. That means that for example e.target works, no need to look for the event object or checking whether it's e.target or e.srcElement (IE). Bubbling and capturing phases also work cross browser. React also takes the liberty of making some small fixes, e.g. the event <input onChange> fires when you type, not when blur away from the input. And of course, event delegation is used as the most efficient way to handle events. You know that "thou shall use event delegation" is also commonly given advice for making web apps snappy.

The good thing about the virtual DOM is that it's all in JavaScript land. You build all your UI in JavaScript. Which means it can be rendered on the server side, so you initial view is fast (and any SEO concerns are addressed). Also, if there are especially heavy operations they can be threaded into WebWorkers, which otherwise have no DOM access.

Read More ...

Markdown in React #

Ben Alpert converted marked, a Markdown Javascript implementation, in React: marked-react. Even without using JSX, the HTML generation is now a lot cleaner. It is also safer as forgetting a call to escape will not introduce an XSS vulnerability.

Unite from BugBusters #

Renault John Lecoultre wrote Unite, an interactive tool for analyzing code dynamically using React. It integrates with CodeMirror.

#reactjs IRC Logs #

Vjeux re-implemented the display part of the IRC logger in React. Just 130 lines are needed for a performant infinite scroll with timestamps and color-coded author names.

View the source on JSFiddle...