There are two types of components you can build within react.js, functional and class components. In this tutorial, you will learn about these two types and by the end, you should feel confident to know when to use each one. Both components has respective pros and cons. By the end of the article, you will understand these differences.
Building a class component is slightly more complex. Instead of defining a function we define a class. The class needs to inherit from 'React.Component'. As class components are not function, you will also need to define a function inside your class to return the HTML, the name of this function is the render(). The same component built using a class component would look like this:
There are several benefits of using functional components. The code to define a functional component is simpler. As most functional components are just functions, writing tests to check that the component works is easier and involves less mocking
Historically, some of the main deciding factors to use a class component was when you needed to manage state or you needed to use a life-cycle hook. React.component comes with several life-cycle hooks/methods that are available for you to hook you can hook into, including:
- componentDidMount() : Called after the component has mounted, e.g. the HTML from render has completed
- shouldComponentUpdate() : Called before the component is re-rendered and when new props or new state
- componentDidUpdate() : called after any rendered HTML has finished loading
For example, componentDidMount() is called after the component is rendered. Constructor() can be used to manage the initialize state. Using these life-cycle hooks we can build complex and feature-rich components.
As of React 16.8 not being able to manage state inside of a functional component is no longer the case. With the introduction of React context/hooks, you can now build a functional component that can also manage state.
Another historic reason to favour a class component was performance. Even though class components are more complex because they were optimized to work with react they actually used to render quicker than the simpler functional components. Again, as of React 15, functional components are just as fast as class components.
Which One Should You Use?
When building a new component I recommend that you favour always starting with a functional component first. If the component needs to get more complex and you need to consider state. First, consider using a hook before just using a class component straightaway.
As React evolves there is less reason to use a class container over a functional component. When writing code it is best to keep it simple. Only convert a component into a class component when you bump into something that you can not do using a functional component.
I have even seen some developers fail a job application as they favoured a class component over a functional component, so beware!