Functional and Class Components in ReactJS

    Jul 18, 2019       by Suraj Roy
functional-class-components.jpg

While working with any of the javascript frameworks today, the Component based approach is very popular we use.

In this article, I am going to explain about the functional components and class components and difference between these.

 

What is a React Component?

Components are the building blocks of any Reactapp and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

 

Functional (Stateless) Components

A functional component is basically a JavaScript function which returns a React element. Its accepts props as argument and returns valid JSX

 
function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}
 

 

that’s a functional component.

The main reason that makes functional component different from a class component is the lack of state and lifecycle methods. This is why functional components are also commonly referred to as stateless components.

the same component written in ES6:

 

 
const Welcome = (props) =><h1>Hello, {props.name}</h1>
 

 

Class (Stateful) Components

Class Components are more complex than functional components including constructors, life-cycle methods, render( ) function and state (data) management. Class components are ES6 classes.

 

 
class Welcome extends Component{
    render(){
        return <div>Hello, {this.props.name}</div>
    }
}

 

In the above code, the Welcome class extends Component, so React understands that this class is a component, and it renders (returns) a React Element.

 

Benefits of using Functional Components

  1. Functional components are easy to test.
  2. It can have better performance.
  3. Functional components are easy to debug.
  4. It end up with less code.
  5. It help you to use best practices.
  6. Functional components can reduce coupling. 

 

Conclusion

Components are the core of React. Having a good knowledge of when and how to use functional & class components makes the React app better performance, readable and testable. You can find more Reactjs Sample Projects here.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

Thanks!


WHAT'S NEW

Find other similar Articles here: