DEV Community

Uma
Uma

Posted on • Edited on

Class and Functional Components

In React we have two types of components: 1. Functional components 2. Class components
We will learn about both types and also discuss the differences between the two but before we do that we need to know what is a “Component”? A component is a function or class that produces JSX to show the user and handle feedback from the user using event handlers. Now,
let's dive in:

Functional Components

Functional components are basically a JavaScript function that produces JSX to show content to the user. It doesn’t have access to the component's lifecycle methods or state. Its only job is to show content to users. Here is an example of a functional component:

const App = () => {
    return <div> Hello World! </div>
}
Enter fullscreen mode Exit fullscreen mode

If you are not familiar with ES6 syntax here is the another example of regular function:

function App() {
   return <div> Hello World! </div>
}
Enter fullscreen mode Exit fullscreen mode

They both return Hello World!. I prefer to use the arrow function as shown in the first example because it will automatically bind this.

Class Components

A class component is a JavaScript class that extends from React which has a render method. We can see we did not have a render method defined in the functional component. This is one difference between both components. Just as the functional component, the class component also produces JSX to show content to the user but it can also use the state system to update content on the screen using setState and in addition use, lifecycle methods to run code at specific points in time. Here is a simple example of a class component:

class App extends React.Component {
   render() {
      return <div> Hello World! </div>
    }
}
Enter fullscreen mode Exit fullscreen mode

There is one more difference between class and function components which is how we pass props. In class components we pass props using this.props but in function components we simply pass props. Let's have a look:

const App = (props) => {
    return <div> My name is  {props.name}! </div>
}

class App extends React.Component {
   render() {
      return <div>My name is {this.props.name}! </div>
    }
}
Enter fullscreen mode Exit fullscreen mode

Everything we discussed above was without the hooks system. With the React hooks system, there is much more we can do with functional components but we will not be exploring the hooks system in this blog post. However, I will say this: In the modern React world the hooks system gives more power to functional components and it functions similarly to that of class components.

Top comments (2)

Collapse
 
alfredrafael profile image
Alfredo Rafael Pabon

Nice article 😃

Collapse
 
uma profile image
Uma

Thank you Alfredo