In the past, there was only one set of React API, now there are two sets: class API and function-based hooks API. Any component can be written by a class or a hook. Here is how to write the class.
Let’s look at the way the hook is written, that is, the function.
These two ways of writing have exactly the same effect. Beginners will naturally ask: “Which API should I use?”
The official recommendation is to use hooks (functions) instead of classes. Because hooks are more concise and less code, they are “lighter” to use, while classes are “heavier”. Moreover, hooks are functions, which are more in line with the functional nature of React.
The following is a comparison of the amount of code for class components (left) and functional components (right). For complex components, the difference is even more.
However, the flexibility of hooks is too great for beginners to understand. Many people have little knowledge and can easily write messy and unmaintainable code. It would be better to use classes. Because classes have many mandatory grammatical constraints, it is not easy to mess up.