The core purpose of a React component is to define the displayed view and bind it to the code that drives its behavior. React’s functional components distill this down to the simplest possible profile: a function that receives properties and returns a JSX definition. Everything required for behavior is defined within the function body, and the class-related parts of object-oriented components are dropped.

Functional components are capable of performing all the work of a class-based component beginning with React 16, via the “hooks” API.

Simple class-based vs. functional comparison

Let’s begin by comparing a very simple class-based component with a functional version.

Listing 1. Simple class-based component

class QuipComponent extends React.Component 
render()
return <p>What gets us into trouble is not what we don't know. It's what we know for sure that just ain't so.</p>;


<div id="app"></div>
ReactDOM.render(<QuipComponent />, document.querySelector("#app"));

Listing 2. Simple functional component

function QuipComponent() 
  return <p>Outside of a dog, a book is a man’s best friend. Inside of a dog, it’s too dark to read.</p>;

<div id="app"></div>
ReactDOM.render(<QuipComponent />, document.querySelector("#app"));

In both cases, the components simply output a paragraph element with content. Notice that the functional version, besides the same call to ReactDOM.render() has no interaction with any APIs. It is just a normal JavaScript function.

This is a small difference, but it is a difference in favor of the simplicity of functional components. In general, any time you can reduce the API footprint of code, it is beneficial to the overall simplicity of the system.

An advantage of object-oriented code is that objects provide a structural organization to the code. In the case of interface components, that structure is provided by the component system itself. A function provides the simplest way to interact with the component rendering engine.

Copyright © 2021 IDG Communications, Inc.