...

/

Introducing the Function Component

Introducing the Function Component

Learn about function components, their properties, and roles in React and understand the parent-child communication mechanism via props.

Types of components

There are mainly two component types that React supports—a class component and a function component.

Class component

React supported the class component from the beginning.

class ClassComponent extends React.Component {
// Render method to display a greeting using the 'name' prop
render() {
// Destructure the 'name' prop from the component's props
const { name } = this.props;
return <h1>Hello, { name }</h1>;
}
}
Sampele of class component

Although the render function of a class component looks quite similar to what a function component returns, and, most of the time, we can convert them in between; the class and function components are treated differently inside the React update process. Therefore, this book intentionally avoids mentioning the class component so as not to confuse any newcomer to React.

In general, a function component can be written shorter and simpler, and it’s also easier in terms of development and testing because it has plain inputs and outputs. Also, it doesn’t have this keyword, which can intimidate new developers or sometimes even senior developers. However, the downside of using a function component is that it’s relatively new to the programming world, and there’s also a mentality shift from Object-Oriented Programming (OOP) to Functional Programming (FP), which can consume us if we are not prepared. Not to mention, being new means, there can be different approaches that we need to learn and absorb before we can address the old problems.

Function component

Other than the class and function components, internally, React actually supports more component types, as in the following example:

import { memo } from 'react';
// Title Component: Memoized functional component rendering an h1 element with "Hello"
const Title = memo(() => <h1>Hello</h1>);
// App Component: Renders the Title Component
const App = () => <Title />;
React funtion component with memoization

When the memo function is applied to the Title component, it creates a component with a component type, MemoComponent. We don’t need to go into the details of these component types, but just know that each component type gets its own update algorithm when updated to the ...