DEV Community

Cover image for React Functional vs Class Components - Beginners Guide.
Abhishek kushwaha
Abhishek kushwaha

Posted on

React Functional vs Class Components - Beginners Guide.

React being one of the famous frontend framework is used for building different kind of user interface. While working with components in JSX we come across two different types of components.

  1. Functional Components
  2. Class Components

In this article we would be looking at how these components are different. So let's get started

Before going into class or functional components let's discuss what's a react component meant to be :

React Component

A component is block of code in which further the components exists to bring any design to small pieces. These are reusable code block and can used or imported independently.
A components play a crucial role while building the complex ui design as we tend to avoid putting everything in a single page.

React has two types of components, lets look into those one by one.

React Functional Components

A Functional Component is basically a JavaScript function that return a React JavaScript Xml element(known as JSX).

Let's have an example to understand

import React from "react";

const Welcome = props => (
  <div>
    <h1>Welcome🙌, {props.name}</h1>
  </div>
);

export default Welcome;
Enter fullscreen mode Exit fullscreen mode

In Functional Components there is no render method , they are mainly responsible for UI presentational like a card or button. If Component needs react state , its advised to go with Functional Components.

React Class Components

Class Component is a regular ES6 class that extends the component class from the react library. To return HTML you have to use render() method in it.
You pass props down to class components and access them with _this.props _

class ClassComponent extends React.Component {
 render() {
   return <h1>Hello, world</h1>;
 }
}

Enter fullscreen mode Exit fullscreen mode

If we want to pass some props for the components:

<Component name = “Abhishek Kushwaha” />

In case of FUNCTIONAL COMPONENT , we pass the props as an argument of our function using the construction “props.name”.

function FunctionalComponent(props) {
 return <h1>Hello, {props.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

With class components, we need to add this. to refer to props.

class ClassComponent extends React.Component {
render() {
 return <h1>Hello, {this.props.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Hope you found Helpful ! 😀

Top comments (2)

Collapse
 
chandanp007 profile image
Chandan Pandey

⭐⭐⭐⭐⭐

Collapse
 
peerreynders profile image
peerreynders

React Docs: Hooks and Function Components.

Not Function-al Component.

I guess they are functional if they work but they are just render functions.