Lesson 3 - Components In React

3.2 - Functional Vs. Class Components

There are two main types of components in React: functional components and class components. Let's learn about them with examples.

Functional Components Functional components are JavaScript functions that return JSX. We already introduced JSX, which allows you to write HTML syntax directly in JavaScript.

Functional Components are easy to write and primarily used to render UI components based on props. We'll learn about props in our next lesson.

The following is a simple functional component:

function App() {
 function Greeting() {
 return <h1>Hello World!</h1>;
 }

 return (
 <>
 <Greeting />
 </>
 );
}

Class Components Class components extend from React.Component and can manage their own state. They have access to lifecycle methods, making them suitable for more complex components that need to handle state or perform side effects. For implementing React's advanced features like Hooks, a more sophisticated syntax is required.

For example,

import React from 'react';

class Car extends React.Component {
 render() {
 return <h2>This is a Car!</h2>;
 }
}

function App() {
 return (
 <>
 <Car />
 </>
 );
}

This table illustrates the difference between functional components and class components.

Functional ComponentsClass Components
Functional components are javascript function that receives props and returns JSXClass components are extended from the React.Component.
Functional components don't require any render function.Class components must have the render function
Functional components are stateless.Class components are stateful.
React lifecycle methods cannot be used in functional components.React lifecycle methods can be used inside class components.
Hooks can be easily used in functional components.Complex syntax is required to implement hooks inside class components