React v15.5.0

April 7, 2017 by Andrew Clark


It's been exactly one year since the last breaking change to React. Our next major release, React 16, will include some exciting improvements, including a complete rewrite of React's internals. We take stability seriously, and are committed to bringing those improvements to all of our users with minimal effort.

To that end, today we're releasing React 15.5.0.

New Deprecation Warnings

The biggest change is that we've extracted React.PropTypes and React.createClass into their own packages. Both are still accessible via the main React object, but using either will log a one-time deprecation warning to the console when in development mode. This will enable future code size optimizations.

These warnings will not affect the behavior of your application. However, we realize they may cause some frustration, particularly if you use a testing framework that treats console.error as a failure.

Adding new warnings is not something we do lightly. Warnings in React are not mere suggestions — they are integral to our strategy of keeping as many people as possible on the latest version of React. We never add warnings without providing an incremental path forward.

So while the warnings may cause frustration in the short-term, we believe prodding developers to migrate their codebases now prevents greater frustration in the future. Proactively fixing warnings ensures you are prepared for the next major release. If your app produces zero warnings in 15.5, it should continue to work in 16 without any changes.

For each of these new deprecations, we've provided a codemod to automatically migrate your code. They are available as part of the react-codemod project.

Migrating from React.PropTypes

Prop types are a feature for runtime validation of props during development. We've extracted the built-in prop types to a separate package to reflect the fact that not everybody uses them.

In 15.5, instead of accessing PropTypes from the main React object, install the prop-types package and import them from there:

// Before (15.4 and below)
import React from 'react';

class Component extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Component.propTypes = {
  text: React.PropTypes.string.isRequired,
}

// After (15.5)
import React from 'react';
import PropTypes from 'prop-types';

class Component extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Component.propTypes = {
  text: PropTypes.string.isRequired,
};

The codemod for this change performs this conversion automatically. Basic usage:

jscodeshift -t react-codemod/transforms/React-PropTypes-to-prop-types.js <path>

The propTypes, contextTypes, and childContextTypes APIs will work exactly as before. The only change is that the built-in validators now live in a separate package.

You may also consider using Flow to statically type check your JavaScript code, including React components.

Migrating from React.createClass

When React was initially released, there was no idiomatic way to create classes in JavaScript, so we provided our own: React.createClass.

Later, classes were added to the language as part of ES2015, so we added the ability to create React components using JavaScript classes. Along with functional components, JavaScript classes are now the preferred way to create components in React.

For your existing createClass components, we recommend that you migrate them to JavaScript classes. However, if you have components that rely on mixins, converting to classes may not be immediately feasible. If so, create-react-class is available on npm as a drop-in replacement:

// Before (15.4 and below)
var React = require('react');

var Component = React.createClass({
  mixins: [MixinA],
  render() {
    return <Child />;
  }
});

// After (15.5)
var React = require('react');
var createReactClass = require('create-react-class');

var Component = createReactClass({
  mixins: [MixinA],
  render() {
    return <Child />;
  }
});

Your components will continue to work the same as they did before.

The codemod for this change attempts to convert a createClass component to a JavaScript class, with a fallback to create-react-class if necessary. It has converted thousands of components internally at Facebook.

Basic usage:

jscodeshift -t react-codemod/transforms/class.js path/to/components

Discontinuing support for React Addons

We're discontinuing active maintenance of React Addons packages. In truth, most of these packages haven't been actively maintained in a long time. They will continue to work indefinitely, but we recommend migrating away as soon as you can to prevent future breakages.

  • react-addons-create-fragment – React 16 will have first-class support for fragments, at which point this package won't be necessary. We recommend using arrays of keyed elements instead.
  • react-addons-css-transition-group - Use react-transition-group/CSSTransitionGroup instead. Version 1.1.1 provides a drop-in replacement.
  • react-addons-linked-state-mixin - Explicitly set the value and onChange handler instead.
  • react-addons-pure-render-mixin - Use React.PureComponent instead.
  • react-addons-shallow-compare - Use React.PureComponent instead.
  • react-addons-transition-group - Use react-transition-group/TransitionGroup instead. Version 1.1.1 provides a drop-in replacement.
  • react-addons-update - Use immutability-helper instead, a drop-in replacement.
  • react-linked-input - Explicitly set the value and onChange handler instead.

We're also discontinuing support for the react-with-addons UMD build. It will be removed in React 16.

React Test Utils

Currently, the React Test Utils live inside react-addons-test-utils. As of 15.5, we're deprecating that package and moving them to react-dom/test-utils instead:

// Before (15.4 and below)
import TestUtils from 'react-addons-test-utils';

// After (15.5)
import TestUtils from 'react-dom/test-utils';

This reflects the fact that what we call the Test Utils are really a set of APIs that wrap the DOM renderer.

The exception is shallow rendering, which is not DOM-specific. The shallow renderer has been moved to react-test-renderer/shallow.

// Before (15.4 and below)
import { createRenderer } from 'react-addons-test-utils';

// After (15.5)
import { createRenderer } from 'react-test-renderer/shallow';

Acknowledgements

A special thank you to these folks for transferring ownership of npm package names:


Installation

We recommend using Yarn or npm for managing front-end dependencies. If you're new to package managers, the Yarn documentation is a good place to get started.

To install React with Yarn, run:

yarn add react@^15.5.0 react-dom@^15.5.0

To install React with npm, run:

npm install --save react@^15.5.0 react-dom@^15.5.0

We recommend using a bundler like webpack or Browserify so you can write modular code and bundle it together into small packages to optimize load time.

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, make sure to compile it in production mode.

In case you don't use a bundler, we also provide pre-built bundles in the npm packages which you can include as script tags on your page:

We've also published version 15.5.0 of the react, react-dom, and addons packages on npm and the react package on bower.


Changelog

15.5.0 (April 7, 2017)

React

  • Added a deprecation warning for React.createClass. Points users to create-react-class instead. (@acdlite in d9a4fa4)
  • Added a deprecation warning for React.PropTypes. Points users to prop-types instead. (@acdlite in 043845c)
  • Fixed an issue when using ReactDOM together with ReactDOMServer. (@wacii in #9005)
  • Fixed issue with Closure Compiler. (@anmonteiro in #8895)
  • Another fix for Closure Compiler. (@Shastel in #8882)
  • Added component stack info to invalid element type warning. (@n3tr in #8495)

React DOM

  • Fixed Chrome bug when backspacing in number inputs. (@nhunzaker in #7359)
  • Added react-dom/test-utils, which exports the React Test Utils. (@bvaughn)

React Test Renderer

  • Fixed bug where componentWillUnmount was not called for children. (@gre in #8512)
  • Added react-test-renderer/shallow, which exports the shallow renderer. (@bvaughn)

React Addons

  • Last release for addons; they will no longer be actively maintained.
  • Removed peerDependencies so that addons continue to work indefinitely. (@acdlite and @bvaughn in 8a06cd7 and 67a8db3)
  • Updated to remove references to React.createClass and React.PropTypes (@acdlite in 12a96b9)
  • react-addons-test-utils is deprecated. Use react-dom/test-utils and react-test-renderer/shallow instead. (@bvaughn)

React v15.4.0

November 16, 2016 by Dan Abramov


Today we are releasing React 15.4.0.

We didn't announce the previous minor releases on the blog because most of the changes were bug fixes. However, 15.4.0 is a special release, and we would like to highlight a few notable changes in it.

Separating React and React DOM

More than a year ago, we started separating React and React DOM into separate packages. We deprecated React.render() in favor of ReactDOM.render() in React 0.14, and removed DOM-specific APIs from React completely in React 15. However, the React DOM implementation still secretly lived inside the React package.

In React 15.4.0, we are finally moving React DOM implementation to the React DOM package. The React package will now contain only the renderer-agnostic code such as React.Component and React.createElement().

This solves a few long-standing issues, such as errors when you import React DOM in the same file as the snapshot testing renderer.

If you only use the official and documented React APIs you won't need to change anything in your application.

However, there is a possibility that you imported private APIs from react/lib/*, or that a package you rely on might use them. We would like to remind you that this was never supported, and that your apps should not rely on internal APIs. The React internals will keep changing as we work to make React better.

Another thing to watch out for is that React DOM Server is now about the same size as React DOM since it contains its own copy of the React reconciler. We don't recommend using React DOM Server on the client in most cases.

Profiling Components with Chrome Timeline

You can now visualize React components in the Chrome Timeline. This lets you see which components exactly get mounted, updated, and unmounted, how much time they take relative to each other.

React components in Chrome timeline

To use it:

  1. Load your app with ?react_perf in the query string (for example, http://localhost:3000/?react_perf).

  2. Open the Chrome DevTools Timeline tab and press Record.

  3. Perform the actions you want to profile. Don't record more than 20 seconds or Chrome might hang.

  4. Stop recording.

  5. React events will be grouped under the User Timing label.

Note that the numbers are relative so components will render faster in production. Still, this should help you realize when unrelated UI gets updated by mistake, and how deep and how often your UI updates occur.

Currently Chrome, Edge, and IE are the only browsers supporting this feature, but we use the standard User Timing API so we expect more browsers to add support for it.

Mocking Refs for Snapshot Testing

If you're using Jest snapshot testing, you might have had issues with components that rely on refs. With React 15.4.0, we introduce a way to provide mock refs to the test renderer. For example, consider this component using a ref in componentDidMount:

import React from 'react';

export default class MyInput extends React.Component {
  componentDidMount() {
    this.input.focus();
  }

  render() {
    return (
      <input
        ref={node => this.input = node}
      />
    );
  }
}

With snapshot renderer, this.input will be null because there is no DOM. React 15.4.0 lets us avoid such crashes by passing a custom createNodeMock function to the snapshot renderer in an options argument:

import React from 'react';
import MyInput from './MyInput';
import renderer from 'react-test-renderer';

function createNodeMock(element) {
  if (element.type === 'input') {
    return {
      focus() {},
    };
  }
  return null;
}

it('renders correctly', () => {
  const options = {createNodeMock};
  const tree = renderer.create(<MyInput />, options);
  expect(tree).toMatchSnapshot();
});

We would like to thank Brandon Dail for implementing this feature.

You can learn more about snapshot testing in this Jest blog post.


Installation

We recommend using Yarn or npm for managing front-end dependencies. If you're new to package managers, the Yarn documentation is a good place to get started.

To install React with Yarn, run:

yarn add react@15.4.0 react-dom@15.4.0

To install React with npm, run:

npm install --save react@15.4.0 react-dom@15.4.0

We recommend using a bundler like webpack or Browserify so you can write modular code and bundle it together into small packages to optimize load time.

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, make sure to compile it in production mode.

In case you don't use a bundler, we also provide pre-built bundles in the npm packages which you can include as script tags on your page:

We've also published version 15.4.0 of the react, react-dom, and addons packages on npm and the react package on bower.


Changelog

React

  • React package and browser build no longer "secretly" includes React DOM.
    (@sebmarkbage in #7164 and #7168)
  • Required PropTypes now fail with specific messages for null and undefined.
    (@chenglou in #7291)
  • Improved development performance by freezing children instead of copying.
    (@keyanzhang in #7455)

React DOM

  • Fixed occasional test failures when React DOM is used together with shallow renderer.
    (@goatslacker in #8097)
  • Added a warning for invalid aria- attributes.
    (@jessebeach in #7744)
  • Added a warning for using autofocus rather than autoFocus.
    (@hkal in #7694)
  • Removed an unnecessary warning about polyfilling String.prototype.split.
    (@nhunzaker in #7629)
  • Clarified the warning about not calling PropTypes manually.
    (@jedwards1211 in #7777)
  • The unstable batchedUpdates API now passes the wrapped function's return value through.
    (@bgnorlov in #7444)
  • Fixed a bug with updating text in IE 8.
    (@mnpenner in #7832)

React Perf

  • When ReactPerf is started, you can now view the relative time spent in components as a chart in Chrome Timeline.
    (@gaearon in #7549)

React Test Utils

  • If you call Simulate.click() on a <input disabled onClick={foo} /> then foo will get called whereas it didn't before.
    (@nhunzaker in #7642)

React Test Renderer

  • Due to packaging changes, it no longer crashes when imported together with React DOM in the same file.
    (@sebmarkbage in #7164 and #7168)
  • ReactTestRenderer.create() now accepts {createNodeMock: element => mock} as an optional argument so you can mock refs with snapshot testing.
    (@Aweary in #7649 and #8261)

Our First 50,000 Stars

September 28, 2016 by Vjeux


Just three and a half years ago we open sourced a little JavaScript library called React. The journey since that day has been incredibly exciting.

Commemorative T-Shirt

In order to celebrate 50,000 GitHub stars, Maggie Appleton from egghead.io has designed us a special T-shirt, which will be available for purchase from Teespring only for a week through Thursday, October 6. Maggie also wrote a blog post showing all the different concepts she came up with before settling on the final design.

React 50k Tshirt

The T-shirts are super soft using American Apparel's tri-blend fabric; we also have kids and toddler T-shirts and baby onesies available.

Proceeds from the shirts will be donated to CODE2040, a nonprofit that creates access, awareness, and opportunities in technology for underrepresented minorities with a specific focus on Black and Latinx talent.

Archeology

We've spent a lot of time trying to explain the concepts behind React and the problems it attempts to solve, but we haven't talked much about how React evolved before being open sourced. This milestone seemed like as good a time as any to dig through the earliest commits and share some of the more important moments and fun facts.

The story begins in our ads org, where we were building incredibly sophisticated client side web apps using an internal MVC framework called BoltJS. Here's a sample of what some Bolt code looked like:

var CarView = require('javelin/core').createClass({
  name: 'CarView',
  extend: require('container').Container,
  properties: {
    wheels: 4,
  },
  declare: function() {
    return {
      childViews: [
        { content: 'I have ' },
        { ref: 'wheelView' },
        { content: ' wheels' }
      ]
    };
  },
  setWheels: function(wheels) {
    this.findRef('wheelView').setContent(wheels);
  },
  getWheels: function() {
    return this.findRef('wheelView').getContent();
  },
});

var car = new CarView();
car.setWheels(3);
car.placeIn(document.body);
//<div>
//  <div>I have </div>
//  <div>3</div>
//  <div> wheels</div>
//</div>

Bolt introduced a number of APIs and features that would eventually make their way into React including render, createClass, and refs. Bolt introduced the concept of refs as a way to create references to nodes that can be used imperatively. This was relevant for legacy interoperability and incremental adoption, and while React would eventually strive to be a lot more functional, refs proved to be a very useful way to break out of the functional paradigm when the need arose.

But as our applications grew more and more sophisticated, our Bolt codebases got pretty complicated. Recognizing some of the framework's shortcomings, Jordan Walke started experimenting with a side-project called FaxJS. His goal was to solve many of the same problems as Bolt, but in a very different way. This is actually where most of React's fundamentals were born, including props, state, re-evaluating large portions of the tree to “diff” the UI, server-side rendering, and a basic concept of components.

TestProject.PersonDisplayer = {
  structure : function() {
    return Div({
      classSet: { personDisplayerContainer: true },
      titleDiv: Div({
        classSet: { personNameTitle: true },
        content: this.props.name
      }),
      nestedAgeDiv: Div({
        content: 'Interests: ' + this.props.interests
      })
    });
  }
};

FBolt is Born

Through his FaxJS experiment, Jordan became convinced that functional APIs — which discouraged mutation — offered a better, more scalable way to build user interfaces. He imported his library into Facebook's codebase in March of 2012 and renamed it “FBolt”, signifying an extension of Bolt where components are written in a functional programming style. Or maybe “FBolt” was a nod to FaxJS – he didn't tell us! ;)

The interoperability between FBolt and Bolt allowed us to experiment with replacing just one component at a time with more functional component APIs. We could test the waters of this new functional paradigm, without having to go all in. We started with the components that were clearly best expressed functionally and then we would later continue to push the boundaries of what we could express as functions.

Realizing that FBolt wouldn't be a great name for the library when used on its own, Jordan Walke and Tom Occhino decided on a new name: “React.” After Tom sent out the diff to rename everything to React, Jordan commented:

Jordan Walke: I might add for the sake of discussion, that many systems advertise some kind of reactivity, but they usually require that you set up some kind of point-to-point listeners and won't work on structured data. This API reacts to any state or property changes, and works with data of any form (as deeply structured as the graph itself) so I think the name is fitting.

Most of Tom's other commits at the time were on the first version of GraphiQL, a project which was recently open sourced.

Adding JSX

Since about 2010 Facebook has been using an extension of PHP called XHP, which enables engineers to create UIs using XML literals right inside their PHP code. It was first introduced to help prevent XSS holes but ended up being an excellent way to structure applications with custom components.

final class :a:post extends :x:element {
  attribute :a;
  protected function render(): XHPRoot {
    $anchor = <a>{$this->getChildren()}</a>;
    $form = (
      <form
        method="post"
        action={$this->:href}
        target={$this->:target}
        class="postLink"
      >{$anchor}</form>
    );
    $this->transferAllAttributes($anchor);
    return $form;
  }
}

Before Jordan's work had even made its way into the Facebook codebase, Adam Hupp implemented an XHP-like concept for JavaScript, written in Haskell. This system enabled you to write the following inside a JavaScript file:

function :example:hello(attrib, children) {
  return (
    <div class="special">
      <h1>Hello, World!</h1>
      {children}
    </div>
  );
}

It would compile the above into the following normal ES3-compatible JavaScript:

function jsx_example_hello(attrib, children) {
  return (
    S.create("div", {"class": "special"}, [
      S.create("h1", {}, ["Hello, World!"]),
      children
    ]
  );
}

In this prototype, S.create would immediately create and return a DOM node. Most of the conversations on this prototype revolved around the performance characteristics of innerHTML versus creating DOM nodes directly. At the time, it would have been less than ideal to push developers universally in the direction of creating DOM nodes directly since it did not perform as well, especially in Firefox and IE. Facebook's then-CTO Bret Taylor chimed in on the discussion at the time in favor of innerHTML over document.createElement:

Bret Taylor: If you are not convinced about innerHTML, here is a small microbenchmark. It is about the same in Chrome. innerHTML is about 30% faster in the latest version of Firefox (much more in previous versions), and about 90% faster in IE8.

This work was eventually abandoned but was revived after React made its way into the codebase. Jordan sidelined the previous performance discussions by introducing the concept of a “Virtual DOM,” though its eventual name didn't exist yet.

Jordan Walke: For the first step, I propose that we do the easiest, yet most general transformation possible. My suggestion is to simply map xml expressions to function call expressions.

  • <x></x> becomes x( )
  • <x height=12></x> becomes x( {height:12} )
  • <x> <y> </y> </x> becomes x({ childList: [y( )] })

At this point, JSX doesn't need to know about React - it's just a convenient way to write function calls. Coincidentally, React's primary abstraction is the function. Okay maybe it's not so coincidental ;)

Adam made a very insightful comment, which is now the default way we write lists in React with JSX.

Adam Hupp: I think we should just treat arrays of elements as a frag. This is useful for constructs like:

<ul>{foo.map(function(i) { return <li>{i.data}</li>; })}</ul>

In this case the ul(..) will get a childList with a single child, which is itself a list.

React didn't end up using Adam's implementation directly. Instead, we created JSX by forking js-xml-literal, a side project by XHP creator Marcel Laverdet. JSX took its name from js-xml-literal, which Jordan modified to just be syntactic sugar for deeply nested function calls.

API Churn

During the first year of React, internal adoption was growing quickly but there was quite a lot of churn in the component APIs and naming conventions:

  • project was renamed to declare then to structure and finally to render.
  • Componentize was renamed to createComponent and finally to createClass.

As the project was about to be open sourced, Lee Byron sat down with Jordan Walke, Tom Occhino and Sebastian Markbåge in order to refactor, reimplement, and rename one of React's most beloved features – the lifecycle API. Lee came up with a well-designed API that is still in place today.

  • Concepts
    • component - a ReactComponent instance
    • state - internal state to a component
    • props - external state to a component
    • markup - the stringy HTML-ish stuff components generate
    • DOM - the document and elements within the document
  • Actions
    • mount - to put a component into a DOM
    • initialize - to prepare a component for rendering
    • update - a transition of state (and props) resulting a render.
    • render - a side-effect-free process to get the representation (markup) of a component.
    • validate - make assertions about something created and provided
    • destroy - opposite of initialize
  • Operands
    • create - make a new thing
    • get - get an existing thing
    • set - merge into existing
    • replace - replace existing
    • receive - respond to new data
    • force - skip checks to do action
  • Notifications
    • shouldObjectAction
    • objectWillAction
    • objectDidAction

Instagram

In 2012, Instagram got acquired by Facebook. Pete Hunt, who was working on Facebook photos and videos at the time, joined their newly formed web team. He wanted to build their website completely in React, which was in stark contrast with the incremental adoption model that had been used at Facebook.

To make this happen, React had to be decoupled from Facebook's infrastructure, since Instagram didn't use any of it. This project acted as a forcing function to do the work needed to open source React. In the process, Pete also discovered and promoted a little project called Webpack. He also implemented the renderToString primitive which was needed to do server-side rendering.

As we started to prepare for the open source launch, Maykel Loomans, a designer on Instagram, made a mock of what the website could look like. The header ended up defining the visual identity of React: its logo and the electric blue color!

React website mock

In its earliest days, React benefited tremendously from feedback, ideas, and technical contributions of early adopters and collaborators all over the company. While it might look like an overnight success in hindsight, the story of React is actually a great example of how new ideas often need to go through several rounds of refinement, iteration, and course correction over a long period of time before reaching their full potential.

React's approach to building user interfaces with functional programming principles has changed the way we do things in just a few short years. It goes without saying, but React would be nothing without the amazing open source community that's built up around it!

Relay: State of the State

August 5, 2016 by Joseph Savona


This month marks a year since we released Relay and we'd like to share an update on the project and what's next.

A Year In Review

A year after launch, we're incredibly excited to see an active community forming around Relay and that companies such as Twitter are using Relay in production:

For a project like mission control, GraphQL and Relay were a near-perfect solution, and the cost of building it any other way justified the investment.

-- Fin Hopkins

This kind of positive feedback is really encouraging (I'll admit to re-reading that post far too many times), and great motivation for us to keep going and make Relay even better.

With the community's help we've already come a long way since the technical preview. Here are some highlights:

  • In March we added support for server-side rendering and for creating multiple instances of Relay on a single page. This was a coordinated effort over the course of several months by community members Denis Nedelyaev and Gerald Monaco (now at Facebook).
  • Also in March we added support for React Native. While we use Relay and React Native together internally, they didn't quite work together in open-source out of the box. We owe a big thanks to Adam Miskiewicz, Tom Burns, Gaëtan Renaudeau, David Aurelio, Martín Bigio, Paul O’Shannessy, Ben Alpert, and many others who helped track down and resolve issues. Finally, thanks to Steven Luscher for coordinating this effort and building the first Relay/ReactNative example app.

We've also seen some great open-source projects spring up around Relay:

This is just a small sampling of the community's contributions. So far we've merged over 300 PRs - about 25% of our commits - from over 80 of you. These PRs have improved everything from the website and docs down the very core of the framework. We're humbled by these outstanding contributions and excited to keep working with each of you!

Retrospective & Roadmap

Earlier this year we paused to reflect on the state of the project. What was working well? What could be improved? What features should we add, and what could we remove? A few themes emerged: performance on mobile, developer experience, and empowering the community.

Mobile Perf

First, Relay was built to serve the needs of product developers at Facebook. In 2016, that means helping developers to build apps that work well on mobile devices connecting on slower networks. For example, people in developing markets commonly use 2011 year-class phones and connect via 2G class networks. These scenarios present their own challenges.

Therefore, one of our primary goals this year is to optimize Relay for performance on low-end mobile devices first, knowing that this can translate to improved performance on high-end devices as well. In addition to standard approaches such as benchmarking, profiling, and optimizations, we're also working on big-picture changes.

For example, in today's Relay, here's what happens when an app is opened. First, React Native starts initializing the JavaScript context (loading and parsing your code and then running it). When this finishes, the app executes and Relay sees that you need data. It constructs and prints the query, uploads the query text to the server, processes the response, and renders your app. (Note that this process applies on the web, except that the code has to be downloaded instead of loaded from the device.)

Ideally, though, we could begin fetching data as soon as the native code had loaded - in parallel with the JS context initialization. By the time your JS code was ready to run, the data-fetching would already be under way. To do this we would need a way to determine statically - at build time - what query an application would send.

The key is that GraphQL is already static - we just need to fully embrace this fact. More on this later.

Developer Experience

Next, we've paid attention to the community's feedback and know that, to put it simply, Relay could be "easier" to use (and "simpler" too). This isn't entirely surprising to us - Relay was originally designed as a routing library and gradually morphed into a data-fetching library. Concepts like Relay "routes", for example, no longer serve as critical a role and are just one more concept that developers have to learn about. Another example is mutations: while writes are inherently more complex than reads, our API doesn't make the simple things simple enough.

Alongside our focus on mobile performance, we've also kept the developer experience in mind as we evolve Relay core.

Empowering the Community

Finally, we want to make it easier for people in the community to develop useful libraries that work with Relay. By comparison, React's small surface area - components - allows developers to build cool things like routing, higher-order components, or reusable text editors. For Relay, this would mean having the framework provide core primitives that users can build upon. We want it to be possible for the community to integrate Relay with view libraries other than React, or to build real-time subscriptions as a complementary library.

What's Next

These were big goals, and also a bit scary; we knew that incremental improvements would only allow us to move so fast. So in April we started a project to build a new implementation of Relay core targeting low-end mobile devices from the start.

As you can guess since we're writing this, the experiment was a success. The result is a new core that retains the best parts of Relay today - colocated components & data-dependencies, automatic data/view consistency, declarative data-fetching - while improving performance on mobile devices and addressing several common areas of confusion.

We're currently focused on shipping the first applications using the new core: ironing out bugs, refining the API changes and developer experience, and adding any missing features. We're excited to bring these changes to open source, and will do so once we've proven them in production. We'll go into more detail in some upcoming talks - links below - but for now here's an overview:

  • Static Queries: By adding a couple of Relay-specific directives, we've been able to retain the expressivity of current Relay queries using static syntax (concretely: you know what query an app will execute just by looking at the source text, without having to run that code). For starters this will allow Relay apps to start fetching data in parallel with JavaScript initialization. But it also unlocks other possibilities: knowing the query ahead of time means that we can generate optimized code for handling query responses, for example, or for reading query data from an offline cache.
  • Expressive Mutations: We'll continue to support a higher-level mutation API for common cases, but will also provide a lower-level API that allows "raw" data access where necessary. If you need to order a list of cached elements, for example, there will be a way to sort() it.
  • Route-less Relay: Routes will be gone in open source. Instead of a route with multiple query definitions, you'll just provide a single query with as many root fields as you want.
  • Cache Eviction/Garbage Collection: The API and architecture is designed from the start to allow removing cached data that is no longer referenced by a mounted view.

Stepping back, we recognize that any API changes will require an investment on your part. To make the transition easier, though, we will continue to support the current API for the foreseeable future (we're still using it too). And as much as possible we will open-source the tools that we use to migrate our own code. Ideas that we're exploring include codemods, an interoperability layer for the old/new APIs, and tutorials & guides to ease migration.

Ultimately, we're making these changes because we believe they make Relay better all around: simpler for developers building apps and faster for the people using them.

Conclusion

If you made it this far, congrats and thanks for reading! We'll be sharing more information about these changes in some upcoming talks:

We can't wait to share the new code with you and are working as fast as we can to do so!

Create Apps with No Configuration

July 22, 2016 by Dan Abramov


Create React App is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration.

Getting Started

Installation

First, install the global package:

npm install -g create-react-app

Node.js 4.x or higher is required.

Creating an App

Now you can use it to create a new app:

create-react-app hello-world

This will take a while as npm installs the transitive dependencies, but once it’s done, you will see a list of commands you can run in the created folder:

created folder

Starting the Server

Run npm start to launch the development server. The browser will open automatically with the created app’s URL.

compiled successfully

Create React App uses both Webpack and Babel under the hood.
The console output is tuned to be minimal to help you focus on the problems:

failed to compile

ESLint is also integrated so lint warnings are displayed right in the console:

compiled with warnings

We only picked a small subset of lint rules that often lead to bugs.

Building for Production

To build an optimized bundle, run npm run build:

npm run build

It is minified, correctly envified, and the assets include content hashes for caching.

One Dependency

Your package.json contains only a single build dependency and a few scripts:

{
  "name": "hello-world",
  "dependencies": {
    "react": "^15.2.1",
    "react-dom": "^15.2.1"
  },
  "devDependencies": {
    "react-scripts": "0.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "eject": "react-scripts eject"
  }
}

We take care of updating Babel, ESLint, and Webpack to stable compatible versions so you can update a single dependency to get them all.

Zero Configuration

It is worth repeating: there are no configuration files or complicated folder structures. The tool only generates the files you need to build your app.

hello-world/
  README.md
  index.html
  favicon.ico
  node_modules/
  package.json
  src/
    App.css
    App.js
    index.css
    index.js
    logo.svg

All the build settings are preconfigured and can’t be changed. Some features, such as testing, are currently missing. This is an intentional limitation, and we recognize it might not work for everybody. And this brings us to the last point.

No Lock-In

We first saw this feature in Enclave, and we loved it. We talked to Ean, and he was excited to collaborate with us. He already sent a few pull requests!

“Ejecting” lets you leave the comfort of Create React App setup at any time. You run a single command, and all the build dependencies, configs, and scripts are moved right into your project. At this point you can customize everything you want, but effectively you are forking our configuration and going your own way. If you’re experienced with build tooling and prefer to fine-tune everything to your taste, this lets you use Create React App as a boilerplate generator.

We expect that at early stages, many people will “eject” for one reason or another, but as we learn from them, we will make the default setup more and more compelling while still providing no configuration.

Try It Out!

You can find Create React App with additional instructions on GitHub.

This is an experiment, and only time will tell if it becomes a popular way of creating and building React apps, or fades into obscurity.

We welcome you to participate in this experiment. Help us build the React tooling that more people can use. We are always open to feedback.

The Backstory

React was one of the first libraries to embrace transpiling JavaScript. As a result, even though you can learn React without any tooling, the React ecosystem has commonly become associated with an overwhelming explosion of tools.

Eric Clemmons called this phenomenon the “JavaScript Fatigue”:

Ultimately, the problem is that by choosing React (and inherently JSX), you’ve unwittingly opted into a confusing nest of build tools, boilerplate, linters, & time-sinks to deal with before you ever get to create anything.

It is tempting to write code in ES2015 and JSX. It is sensible to use a bundler to keep the codebase modular, and a linter to catch the common mistakes. It is nice to have a development server with fast rebuilds, and a command to produce optimized bundles for production.

Combining these tools requires some experience with each of them. Even so, it is far too easy to get dragged into fighting small incompatibilities, unsatisfied peerDependencies, and illegible configuration files.

Many of those tools are plugin platforms and don’t directly acknowledge each other’s existence. They leave it up to the users to wire them together. The tools mature and change independently, and tutorials quickly get out of date.

This doesn’t mean those tools aren’t great. To many of us, they have become indispensable, and we very much appreciate the effort of their maintainers. They already have too much on their plates to worry about the state of the React ecosystem.

Still, we knew it was frustrating to spend days setting up a project when all you wanted was to learn React. We wanted to fix this.

Could We Fix This?

We found ourselves in an unusual dilemma.

So far, our strategy has been to only release the code that we are using at Facebook. This helped us ensure that every project is battle-tested and has clearly defined scope and priorities.

However, tooling at Facebook is different than at many smaller companies. Linting, transpilation, and packaging are all handled by powerful remote development servers, and product engineers don’t need to configure them. While we wish we could give a dedicated server to every user of React, even Facebook cannot scale that well!

The React community is very important to us. We knew that we couldn’t fix the problem within the limits of our open source philosophy. This is why we decided to make an exception, and to ship something that we didn’t use ourselves, but that we thought would be useful to the community.

The Quest for a React CLI

Having just attended EmberCamp a week ago, I was excited about Ember CLI. Ember users have a great “getting started” experience thanks to a curated set of tools united under a single command-line interface. I have heard similar feedback about Elm Reactor.

Providing a cohesive curated experience is valuable by itself, even if the user could in theory assemble those parts themselves. Kathy Sierra explains it best:

If your UX asks the user to make choices, for example, even if those choices are both clear and useful, the act of deciding is a cognitive drain. And not just while they’re deciding... even after we choose, an unconscious cognitive background thread is slowly consuming/leaking resources, “Was that the right choice?”

I never tried to write a command-line tool for React apps, and neither has Christopher. We were chatting on Messenger about this idea, and we decided to work together on it for a week as a hackathon project.

We knew that such projects traditionally haven’t been very successful in the React ecosystem. Christopher told me that multiple “React CLI” projects have started and failed at Facebook. The community tools with similar goals also exist, but so far they have not yet gained enough traction.

Still, we decided it was worth another shot. Christopher and I created a very rough proof of concept on the weekend, and Kevin soon joined us.

We invited some of the community members to collaborate with us, and we have spent this week working on this tool. We hope that you’ll enjoy using it! Let us know what you think.

We would like to express our gratitude to Max Stoiber, Jonny Buchanan, Ean Platter, Tyler McGinnis, Kent C. Dodds, and Eric Clemmons for their early feedback, ideas, and contributions.