Components and props

Now that you know about React elements, we can go one level higher and finally look at how to write components.

React components, like Vue.js or Angular ones, are all about composing user interfaces from small and reusable pieces. Of course, components are meant to be composed together. To compose components, you can simply refer to those in JSX code or using React.createElement(...​) calls.

Interestingly, in React, there is no need to register components as we need to with Angular. Components that are used just need to be in scope where they are used (that is, they either need to be imported or declared before they are used).

Conceptually, React components are really straightforward: they accept a single (immutable!) props object as input. As output, they return JSX (or React.createElement(...​) calls) and, hence, React elements.

As we just learned in the previous section, React elements are simply immutable descriptors for a part of the user interface.

With React, we never instantiate components ourselves. Instead, React takes care of this for us. The reason for this is that React can optimize things much further by keeping control over the base lifecycle of components. It can actually render components lazily.

This also means that React has the same issues as Vue.js with dependency injection libraries such as Inversify. The solution that we applied in the previous chapter actually works with React as well.

React's name comes from its reactivity. When component inputs change (that is, its props), then its output changes as well; a new React element is created and passed to the renderer, which takes care of efficiently updating the target (for example, the DOM).

With React, components can be defined as follows:

Whether you use pure functions or class components, it is important to keep in mind that the props object (that is, the component inputs) must never be mutated by the component.

We'll quickly explore both approaches in the following sections.