Difference between Functional and Class components in React.

If you’ve ever used React before, then you’ve definitely come across both those components mentioned in the title of the blog. In this blog, I will be providing you with the differences of the two components.

In React, the simplest way to show what you a Functional component would look like, is basically just this:

function Component(props) {
return (
<div>
<h1> Hi {props.name}, welcome to the component.</h1>
</div>
);
}

Compared to the functional component above, the way to write out a simple Class component would be this:

class DifferentComponent extends React.Component {
render() {
return <h1> Hi, {this.props.name}. </h1>
};
};

Now you may be wondering, why should I choose one over the other? Well, let’s get to it!

A functional component is just a regular plain old JavaScript function that simply returns HTML UI. People would also refer to this component as the “Stateless component” because they accept data that you would mainly render out onto the page. It accepts props, and returns JSX. This component also doesn’t come with a state, but as of recent updates with React, you can have a state inside of our “stateless components”. Previously in React, there was no such thing as LifeCycle method, but recently updates were made to include those into our stateless components. If you look at the two components, you will also see that the Functional component doesn’t not have a render method used, and lastly, you can typically write these functional components out as a regular function, or using ES6 syntax with their new arrow function.

As opposed to the Functional component, we have the Class component. Our class component is a regular ES6 class that extends component class from the React library. This component also has a nickname called “stateful component” because they introduce logic and our state, it has a render method that returns to us our JSX, it introduces another layer of complex UI logic, you pass props to class components and access this with “this.props”, and also we are introduced to the LifeCycle methods that we can include in our component.

Now you may be asking yourself, why would I want to use the Functional component over the Class component considering how much it doesn’t have? Well, some reasons to use them are simply listed as:

Hopefully this blog has helped you out with understanding the differences between the two components, and knowing when to use one as opposed to the other. I will also provide some documentation to help you further your knowledge of React!

Programmer