The Two Types of React Components
Distinguish between the different kinds of components and practice them yourself in this lesson.
Components are relatively easy to explain. They allow us to de-construct complex user interfaces into multiple parts. Ideally, these parts are reusable, isolated, and self-contained. They can deal with any input from the outside and describe what will be rendered on the screen by whatever they define in the render()
method.
We can cluster components into two different versions:
- Function components, which are
expressed in the form of a function.
- Class components, which build upon the newly introduced ES2015 classes.
Until recently, the term stateless functional component was prevalent because the state could only be managed in class components before the introduction of React Hooks. From React 16.8.0
onwards, the state is managed using Hooks.
Function components
The simplest way to define a React component is through a function component. You might have guessed it, function components are just regular JavaScript functions:
function Hello(props) {
return <div>Hello {props.name}</div>;
}
To be classified as a valid React component, the function has to fulfill two criteria:
- It has to either return an explicit
null
(undefined
is not allowed) or a validReact.element
(in the form of JSX). - It receives a props object.
Note: Props object can be optional and take
null
as an argument.
Provided below is the snippet for a function component. Go ahead and run the code.
Get hands-on with 1400+ tech skills courses.