How do you make a component stateless?

Question

In the context of this exercise, how do you make a component stateless?

Answer

There are a few ways to make stateless components. The two most common ways are as follows.

One is to define a class by extending React.Component, and excluding a constructor method and ensuring that it does not use the this.setState() and this.getState() methods. By creating a stateless component this way, the component will be able to access all component lifecycle methods.

class Example extends React.Component {
  render() {
    return ...
  }
}

Another way is creating a functional component, which takes in props and returns a React element. Unlike the previous method, however, functional components will not have access to the lifecycle methods.

function Example(props) {
  return ...
}
12 Likes