Class components versus functional components
We just defined React components as functions that return a piece of the UI. This is a useful way of thinking about them, and is certainly true for our App
component. However, there's another way of writing React components.
Right now, our App
component is a functional component. This means it's literally written as a function, but you can also write components as JavaScript classes. These are called class-based or stateful components (we'll talk about the stateful part in a bit).
JavaScript classes are a new feature of ES6. They work in a similar (but not identical) way to classes in other languages. We won't delve too deep into them here, but for our purpose, you can do the following:
- Have a class extend another class (and inherit its properties)
- Create an instance of a class with the new keyword (that is, instantiate it)
Let's see an example by converting our App
component into a class-based component.
Every class component must do two things: it...