# Class vs Functional Components
In the world of React, there are two ways of writing a React component. One uses a function and the other uses a class. Recently functional components are becoming more and more popular, so why is that?
Lets see some main differences.
# Rendering JSX
First of all, the clear difference is the syntax. Just like in their names, a functional component is just a plain JavaScript function that returns JSX. A class component is a JavaScript class that extends React.Component which has a render method. A bit confusing? Let’s take a look into a simple example.
import React from 'react';
function FunctionalComponent() {
return <h1>Hello world</h1>;
}
As you can see, a functional component is a function that return JSX.
TIP
You can also use arrow functions for functional components.
On the other hand, when defining a class component you have to make a class that extends React.Component. The JSX to render will be returned inside the render method.
import React, { Component } from 'react';
class ClassComponent extends Component {
render() {
return <h1>Hello, world</h1>;
}
}
# Passing Props
On a previous chapter we already saw how Class Components handle props. So now lets take a look on how Functional Components does.
const MyName = (props) => {
return <div>Hello, {props.name}</div>;
};
TIP
Destructuring props: { name }
# Handling State
Handling state was only doable in a Class Component until React 16.8 was released. They introduced useState Hook, which we havent learned yet, but we will see a brief example here.
Please read official docs (opens new window)
import React, { useState } from 'react';
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
);
};
You can try and play with this in this CodeSandbox (opens new window)
To use state variables in a functional component, we need to use useState Hook, which takes an argument of initial state. In this case we start with 0 clicks so the initial state of count will be 0.
Of course you can have more variety of initial state including null, string, or even object - any type that JavaScript allows! And on the left side, as useState returns the current state and a function that updates it, we are destructuring the array like this. If you are a bit confused about the two elements of the array, you can consider them as a state and its setter. In this example we named them count and setCount to make it easy to understand the connection between the two.