React Stateless Functional Components

What are React Stateless Functional Components?

React stateless functional components are pure JavaScript functions that only have a render() function and no lifecycle methods like componentDidMount.

React

Advantages of Stateless Functional Components

Let’s look at why Stateless Functional Components beneficial.

No this keyword

No need of classes means, you don’t have to bind the callbacks to the class.

// With classes
onClick={this.sayHello.bind(this)}>Say Hello</a>
// Without classes
onClick={sayHello}>Say Hi</a>

This will be helpful for the developers who are struggling with understanding this keyword.

No Classes Required

Not using classes means we can avoid using classes! That also means we can do without extends and constructor.

Leave state to the container

Stateless functional components are best for the presentational components, which focus on the UI. This will leave container components to manage the state and pass down data as props to the presentational components.

Less Noise

Stateless functional components require less lines of code compared to classes.

import React from 'react';

class Car extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        {`Brand: ${this.props.brand}`}
      </div>
    );
  }
}

export default Car;

By using stateless functional components, this can be written in lesser number of lines.

import React from 'react';

const Car = ({brand}) => {
    return (
      <div>
        {`Brand: ${brand}`}
      </div>
    );
};

export default Car;

Best Practice

Presentational components focus solely on the UI, so state should be avoided in them. Only container components should handle lifecycle hooks. This makes functional components an ideal candidate for this role.

High Testability

Stateless functional components can be easily tested in pure isolation. Not having to deal with state, makes this an easy task.

Performant

No state management and lifecycle methods means there’s no need to allocated memory for those components. This results in improved performance.

Conclusion

React’s stateless functional components bring us highly performant, testable, and readable way of writing components.

Be first to comment

Leave a Reply