React Components, Elements, and Instances

December 18, 2015 by Dan Abramov


The difference between components, their instances, and elements confuses many React beginners. Why are there three different terms to refer to something that is painted on screen?

Managing the Instances #

If you’re new to React, you probably only worked with component classes and instances before. For example, you may declare a Button component by creating a class. When the app is running, you may have several instances of this component on screen, each with its own properties and local state. This is the traditional object-oriented UI programming. Why introduce elements?

In this traditional UI model, it is up to you to take care of creating and destroying child component instances. If a Form component wants to render a Button component, it needs to create its instance, and manually keep it up to date with any new information.

class Form extends TraditionalObjectOrientedView {
  render() {
    // Read some data passed to the view
    const { isSubmitted, buttonText } = this.attrs;

    if (!isSubmitted && !this.button) {
      // Form is not yet submitted. Create the button!
      this.button = new Button({
        children: buttonText,
        color: 'blue'
      });
      this.el.appendChild(this.button.el);
    }

    if (this.button) {
      // The button is visible. Update its text!
      this.button.attrs.children = buttonText;
      this.button.render();
    }

    if (isSubmitted && this.button) {
      // Form was submitted. Destroy the button!
      this.el.removeChild(this.button.el);
      this.button.destroy();
    }

    if (isSubmitted && !this.message) {
      // Form was submitted. Show the success message!
      this.message = new Message({ text: 'Success!' });
      this.el.appendChild(this.message.el);
    }
  }
}

This is pseudocode, but it is more or less what you end up with when you write composite UI code that behaves consistently in an object-oriented way using a library like Backbone.

Each component instance has to keep references to its DOM node and to the instances of the children components, and create, update, and destroy them when the time is right. The lines of code grow as the square of the number of possible states of the component, and the parents have direct access to their children component instances, making it hard to decouple them in the future.

So how is React different?

Elements Describe the Tree #

In React, this is where the elements come to rescue. An element is a plain object describing a component instance or DOM node and its desired properties. It contains only information about the component type (for example, a Button), its properties (for example, its color), and any child elements inside it.

An element is not an actual instance. Rather, it is a way to tell React what you want to see on the screen. You can’t call any methods on the element. It’s just an immutable description object with two fields: type: (string | ReactClass) and props: Object1.

DOM Elements #

When an element’s type is a string, it represents a DOM node with that tag name, and props correspond to its attributes. This is what React will render. For example:

{
  type: 'button',
  props: {
    className: 'button button-blue',
    children: {
      type: 'b',
      props: {
        children: 'OK!'
      }
    }
  }
}

This element is just a way to represent the following HTML as a plain object:

<button class='button button-blue'>
  <b>
    OK!
  </b>
</button>

Note how elements can be nested. By convention, when we want to create an element tree, we specify one or more child elements as the children prop of their containing element.

What’s important is that both child and parent elements are just descriptions and not the actual instances. They don’t refer to anything on the screen when you create them. You can create them and throw them away, and it won’t matter much.

React elements are easy to traverse, don’t need to be parsed, and of course they are much lighter than the actual DOM elements—they’re just objects!

Component Elements #

However, the type of an element can also be a function or a class corresponding to a React component:

{
  type: Button,
  props: {
    color: 'blue',
    children: 'OK!'
  }
}

This is the core idea of React.

An element describing a component is also an element, just like an element describing the DOM node. They can be nested and mixed with each other.

This feature lets you define a DangerButton component as a Button with a specific color property value without worrying about whether Button renders to a DOM <button>, a <div>, or something else entirely:

const DangerButton = ({ children }) => ({
  type: Button,
  props: {
    color: 'red',
    children: children
  }
});

You can mix and match DOM and component elements in a single element tree:

const DeleteAccount = () => ({
  type: 'div',
  props: {
    children: [{
      type: 'p',
      props: {
        children: 'Are you sure?'
      }
    }, {
      type: DangerButton,
      props: {
        children: 'Yep'
      }
    }, {
      type: Button,
      props: {
        color: 'blue',
        children: 'Cancel'
      }
   }]
});

Or, if you prefer JSX:

const DeleteAccount = () => (
  <div>
    <p>Are you sure?</p>
    <DangerButton>Yep</DangerButton>
    <Button color='blue'>Cancel</Button>
  </div>
);

This mix and matching helps keep components decoupled from each other, as they can express both is-a and has-a relationships exclusively through composition:

  • Button is a DOM <button> with specific properties.
  • DangerButton is a Button with specific properties.
  • DeleteAccount contains a Button and a DangerButton inside a <div>.

Components Encapsulate Element Trees #

When React sees an element with a function or class type, it knows to ask that component what element it renders to, given the corresponding props.

When it sees this element:

{
  type: Button,
  props: {
    color: 'blue',
    children: 'OK!'
  }
}

React will ask Button what it renders to. The Button will return this element:

{
  type: 'button',
  props: {
    className: 'button button-blue',
    children: {
      type: 'b',
      props: {
        children: 'OK!'
      }
    }
  }
}

React will repeat this process until it knows the underlying DOM tag elements for every component on the page.

React is like a child asking “what is Y” for every “X is Y” you explain to them until they figure out every little thing in the world.

Remember the Form example above? It can be written in React as follows1:

const Form = ({ isSubmitted, buttonText }) => {
  if (isSubmitted) {
    // Form submitted! Return a message element.
    return {
      type: Message,
      props: {
        text: 'Success!'
      }
    };
  }

  // Form is still visible! Return a button element.
  return {
    type: Button,
    props: {
      children: buttonText,
      color: 'blue'
    }
  };
};

That’s it! For a React component, props are the input, and an element tree is the output.

The returned element tree can contain both elements describing DOM nodes, and elements describing other components. This lets you compose independent parts of UI without relying on their internal DOM structure.

We let React create, update, and destroy instances. We describe them with elements we return from the components, and React takes care of managing the instances.

Components Can Be Classes or Functions #

In the code above, Form, Message, and Button are React components. They can either be written as functions, like above, or as classes descending from React.Component. These three ways to declare a component are mostly equivalent:

// 1) As a function of props
const Button = ({ children, color }) => ({
  type: 'button',
  props: {
    className: 'button button-' + color,
    children: {
      type: 'b',
      props: {
        children: children
      }
    }
  }
});

// 2) Using the React.createClass() factory
const Button = React.createClass({
  render() {
    const { children, color } = this.props;
    return {
      type: 'button',
      props: {
        className: 'button button-' + color,
        children: {
          type: 'b',
          props: {
            children: children
          }
        }
      }
    };
  }
});

// 3) As an ES6 class descending from React.Component
class Button extends React.Component {
  render() {
    const { children, color } = this.props;
    return {
      type: 'button',
      props: {
        className: 'button button-' + color,
        children: {
          type: 'b',
          props: {
            children: children
          }
        }
      }
    };
  }
}

When a component is defined as a class, it is a little bit more powerful than a functional component. It can store some local state and perform custom logic when the corresponding DOM node is created or destroyed.

A functional component is less powerful but is simpler, and acts like a class component with just a single render() method. Unless you need features available only in a class, we encourage you to use functional components instead.

However, whether functions or classes, fundamentally they are all components to React. They take the props as their input, and return the elements as their output.

Top-Down Reconciliation #

When you call:

ReactDOM.render({
  type: Form,
  props: {
    isSubmitted: false,
    buttonText: 'OK!'
  }
}, document.getElementById('root'));

React will ask the Form component what element tree it returns, given those props. It will gradually “refine” its understanding of your component tree in terms of simpler primitives:

// React: You told me this...
{
  type: Form,
  props: {
    isSubmitted: false,
    buttonText: 'OK!'
  }
}

// React: ...And Form told me this...
{
  type: Button,
  props: {
    children: 'OK!',
    color: 'blue'
  }
}

// React: ...and Button told me this! I guess I'm done.
{
  type: 'button',
  props: {
    className: 'button button-blue',
    children: {
      type: 'b',
      props: {
        children: 'OK!'
      }
    }
  }
}

This is a part of the process that React calls reconciliation which starts when you call ReactDOM.render() or setState(). By the end of the reconciliation, React knows the result DOM tree, and a renderer like react-dom or react-native applies the minimal set of changes necessary to update the DOM nodes (or the platform-specific views in case of React Native).

This gradual refining process is also the reason React apps are easy to optimize. If some parts of your component tree become too large for React to visit efficiently, you can tell it to skip this “refining” and diffing certain parts of the tree if the relevant props have not changed. It is very fast to calculate whether the props have changed if they are immutable, so React and immutability work great together, and can provide great optimizations with the minimal effort.

You might have noticed that this blog entry talks a lot about components and elements, and not so much about the instances. The truth is, instances have much less importance in React than in most object-oriented UI frameworks.

Only components declared as classes have instances, and you never create them directly: React does that for you. While mechanisms for a parent component instance to access a child component instance exist, they are only used for imperative actions (such as setting focus on a field), and should generally be avoided.

React takes care of creating an instance for every class component, so you can write components in an object-oriented way with methods and local state, but other than that, instances are not very important in the React’s programming model and are managed by React itself.

Summary #

An element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.

A component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns an element tree as the output.

When a component receives some props as an input, it is because a particular parent component returned an element with its type and these props. This is why people say that the props flows one way in React: from parents to children.

An instance is what you refer to as this in the component class you write. It is useful for storing local state and reacting to the lifecycle events.

Functional components don’t have instances at all. Class components have instances, but you never need to create a component instance directly—React takes care of this.

Finally, to create elements, use React.createElement(), JSX, or an element factory helper. Don’t write elements as plain objects in the real code—just know that they are plain objects under the hood.

Further Reading #


  1. All React elements require an additional $$typeof: Symbol.for('react.element') field declared on the object for security reasons. It is omitted in the examples above. This blog entry uses inline objects for elements to give you an idea of what’s happening underneath but the code won’t run as is unless you either add $$typeof to the elements, or change the code to use React.createElement() or JSX. 

isMounted is an Antipattern

December 16, 2015 by Jim Sproch


As we move closer to officially deprecating isMounted, it's worth understanding why the function is an antipattern, and how to write code without the isMounted function.

The primary use case for isMounted() is to avoid calling setState() after a component has unmounted, because calling setState() after a component has unmounted will emit a warning. The “setState warning” exists to help you catch bugs, because calling setState() on an unmounted component is an indication that your app/component has somehow failed to clean up properly. Specifically, calling setState() in an unmounted component means that your app is still holding a reference to the component after the component has been unmounted - which often indicates a memory leak!

To avoid the error message, people often add lines like this:

if(this.isMounted()) { // This is bad.
  this.setState({...});
}

Checking isMounted before calling setState() does eliminate the warning, but it also defeats the purpose of the warning, since now you will never get the warning (even when you should!)

Other uses of isMounted() are similarly erroneous; using isMounted() is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.

An easy migration strategy for anyone upgrading their code to avoid isMounted() is to track the mounted status yourself. Just set a _isMounted property to true in componentDidMount and set it to false in componentWillUnmount, and use this variable to check your component's status.

An optimal solution would be to find places where setState() might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount, prior to unmounting.

For instance, if you are using a Flux store in your component, you must unsubscribe in componentWillUnmount:

class MyComponent extends React.Component {
  componentDidMount() {
    mydatastore.subscribe(this);
  }
  render() {
    ...
  }
  componentWillUnmount() {
    mydatastore.unsubscribe(this);
  }
}

If you use ES6 promises, you may need to wrap your promise in order to make it cancelable.

const cancelablePromise = makeCancelable(
  new Promise(r => component.setState({...}}))
);

cancelablePromise
  .promise
  .then(() => console.log('resolved'))
  .catch((reason) => console.log('isCanceled', reason.isCanceled));

cancelablePromise.cancel(); // Cancel the promise

Where makeCancelable is defined by @istarkov as:

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  return {
    promise: new Promise(
      (resolve, reject) => promise
        .then(r => hasCanceled_
          ? reject({isCanceled: true})
          : resolve(r)
        )
    ),
    cancel() {
      hasCanceled_ = true;
    },
  };
};

As an added bonus for getting your code cleaned up early, getting rid of isMounted() makes it one step easier for you to upgrade to ES6 classes, where using isMounted() is already prohibited. Happy coding!

React.js Conf 2016 Diversity Scholarship

December 4, 2015 by Paul O’Shannessy


I am thrilled to announced that we will be organizing another diversity scholarship program for the upcoming React.js Conf! The tech industry is suffering from a lack of diversity, but it's important to us that we have a thriving community that is made up of people with a variety of experiences and viewpoints.

When we ran this program last year, we had over 200 people apply for only 10 tickets. There were so many people that we wanted to bring in but we couldn't. The results were still awesome, and we had bright individuals from around the world attending who would have otherwise been unable to. These attendees took part in discussions at the conference and brought perspectives that we might not have otherwise seen there.

This year we're excited to bring back the scholarship, but we've set aside 40 tickets because we really believe that it's important to do our best to make sure we have an even more diverse audience.

This is something I'm personally really excited to be a part of. I know the rest of the team is as well. We're really proud to have everyone at Facebook providing support and funding for this.

The details of the scholarship are provided below (or you can go directly to the application). I encourage you to apply! If you don't feel like you are eligible yourself, you can still help – send this along to friends, family, coworkers, acquaintances, or anybody who might be interested. And even if you haven't spoken before, please consider submitting a proposal for a talk (either 30 minutes or just 5 minutes) - we're hoping to have a very diverse group of speakers in addition to attendees.


Facebook is excited to announce that we are now accepting applications for the React.js Conf Diversity Scholarship!

Beginning today, those studying or working in computer science or a related field can apply for a partial scholarship to attend the React.js Conf in San Francisco, CA on February 22 & 23, 2016.

React opens a world of new possibilities such as server-side rendering, real-time updates, different rendering targets like SVG and canvas. React Native makes is easy to use the same concepts and technologies to build native mobile experiences on iOS and Android. Join us at React.js Conf to shape the future of client-side applications! For more information about the React.js conference, please see the website.

At Facebook, we believe that anyone anywhere can make a positive impact by developing products to make the world more open and connected to the people and things they care about. Given the current realities of the tech industry and the lack of representation of communities we seek to serve, applicants currently under-represented in Computer Science and related fields are strongly encouraged to apply. Facebook will make determinations on scholarship recipients in its sole discretion. Facebook complies with all equal opportunity laws.

To apply for the scholarship, please visit the application page: http://goo.gl/forms/PEmKj8oUp4

Award Includes #

  • Paid registration fee for the React.js Conf Feburary 22 & 23 in downtown San Francisco, CA
  • Paid lodging expenses for February 21, 22, 23

Important Dates #

  • Sunday December 13th 2015 - 11:59 PST: Applications for the React.js Conf Scholarship must be submitted in full
  • Wednesday, December 16th, 2015: Award recipients will be notified by email of their acceptance
  • Monday & Tuesday, February 22 & 23, 2016: React.js Conf

Eligibility #

  • Must currently be studying or working in Computer Science or a related field
  • International applicants are welcome, but you will be responsible for securing your own visa to attend the conference
  • You must be able to provide your own transportation to San Francisco
  • You must be available to attend the full duration of React.js Conf on February 22 & 23 in San Francisco, CA

React v0.14.3

November 18, 2015 by Paul O’Shannessy


It's time for another installment of React patch releases! We didn't break anything in v0.14.2 but we do have a couple of other bugs we're fixing. The biggest change in this release is actually an addition of a new built file. We heard from a number of people that they still need the ability to use React to render to a string on the client. While the use cases are not common and there are other ways to achieve this, we decided that it's still valuable to support. So we're now building react-dom-server.js, which will be shipped to Bower and in the dist/ directory of the react-dom package on npm. This file works the same way as react-dom.js and therefore requires that the primary React build has already been included on the page.

The release is now available for download:

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


Changelog #

React DOM #

  • Added support for nonce attribute for <script> and <style> elements
  • Added support for reversed attribute for <ol> elements

React TestUtils Add-on #

  • Fixed bug with shallow rendering and function refs

React CSSTransitionGroup Add-on #

  • Fixed bug resulting in timeouts firing incorrectly when mounting and unmounting rapidly

React on Bower #

  • Added react-dom-server.js to expose renderToString and renderToStaticMarkup for usage in the browser

React v0.14.2

November 2, 2015 by Paul O’Shannessy


We have a quick update following the release of 0.14.1 last week. It turns out we broke a couple things in the development build of React when using Internet Explorer. Luckily it was only the development build, so your production applications were unaffected. This release is mostly to address those issues. There is one notable change if consuming React from npm. For the react-dom package, we moved react from a regular dependency to a peer dependency. This will impact very few people as these two are typically installed together at the top level, but it will fix some issues with dependencies of installed components also using react as a peer dependency.

The release is now available for download:

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


Changelog #

React DOM #

  • Fixed bug with development build preventing events from firing in some versions of Internet Explorer & Edge
  • Fixed bug with development build when using es5-sham in older versions of Internet Explorer
  • Added support for integrity attribute
  • Fixed bug resulting in children prop being coerced to a string for custom elements, which was not the desired behavior.
  • Moved react from dependencies to peerDependencies to match expectations and align with react-addons-* packages