4 Functional Components

 

This chapter covers

  • Introducing functional components
  • Comparing functional components to class-based components
  • Choosing between the two types of component definitions
  • Converting a class-based component to a functional component

React was based on class-based components for a long time in the early years, but an alternative came along for the simplest of components at some point. Functional components are a more succinct and, in some regards, simpler way of writing React components, and they now have the same feature set as their class-based cousins.

The term functional component isn’t meant as a contrast to a nonfunctional component—no one has any use for those. Rather, the functional part refers to the component definition itself being a JavaScript function rather than a JavaScript class.

In the beginning, functional components were less powerful than class-based components, but when React hooks came about in React 16.8, functional components were suddenly as powerful, if not more, than their class-based siblings. Today, many React developers exclusively use functional components, as they are the primary method recommended by the React team.

Class-based components are still fully supported in React and probably not going anywhere anytime soon. You’ll also find them very common “in the wild,” for several reasons:

4.1 The shorter way to write React components

4.1.1 An example application

4.1.2 Destructuring properties

4.1.3 Default values

4.1.4 Pass-through properties

4.2 A comparison of component types

4.2.1 Benefits of functional components

4.2.2 Disadvantages of functional components

4.2.3 Nonfactors between component types

4.2.4 Choosing the component type

4.3 When not to use a functional component

4.3.1 Error boundary

4.3.2 Codebase is class-based