stateless vs stateful component in ReactJS

While creating a project in ReactJS, you will be creating components. There are two kinds of a component.

  • Stateless component ( Functional component )
  • Stateful component ( Class component )

Stateless component ( Functional component )

Stateless component as the name suggests, does not have any state object. This component is simple JavaScript function which takes props as an argument and returns JSX element.
Let us have a look at an example.


const StateLessComp = props => {
    return (
        <div>
            props.description
        </div>
    );
}
                    

As per above code, it is just a simple function which uses props as argument and returns JSX element.
You can import this component and use it in any other component as <StateLessComp />.

Stateful component ( Class component )

Stateful component as the name suggests, does have state ( component related data ). This component can have state, component life cycle methods and hooks.
Let us have a look at an example.


class StateFulComp extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            ...
        }
        // Use constructor only when needed.
    }
    render(){
        return(
            <div>
                this.props.description
            </div>
        );
    }
}
                    

As per above code, Classful component is created with class and it can have constructor ( only needed when you need to add state ) with super(props). render method is same as the stateless function. It returns JSX element. To access props, you can use this keyword.

Stateless or Stateful, which one to use?

As a beginner, you can be confused about what should you use? Stateless or Stateful?
We will see all the factors one by one.

state object or lifecycle methods

Whenever you need to use state or any lifecycle method of component or hooks, you have to use a stateful ( Class ) component. Because the stateless ( Functional ) component can not have any of them.

Size of code

When a component is simple and does not need any state or lifecycle method, then it is advisable to use a stateless component over a stateful component because of the size of the code after compile ( to ES5 code ).

Suppose stateful and stateless components have the same code ( just a button ) and when you compile it, the size of the stateful component is much big than stateless component.

So a stateless component is much better than stateful for the component which only has props.

In the case of performance, both are the same.

Conclusion

In this section, we have learned about difference between stateful component and stateless component.
In the next section, you will learn about component lifecycle methods in ReactJS.