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.
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.
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:
- Using pure functions: These are called function components (heavily recommended).
- Using classes: These are called class components.
We'll quickly explore both approaches in the following sections.