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

What’s a use case for functional components and class components? I’ve heard that React has been moving away from lifecycle methods, but I don’t see why.

5 Likes

seems like we’ll just have to keep going with the lesson, lol. I’m assuming though, it’s so we don’t have state littered through out the app/website. since we can pass props to child components and even use react lifecycle methods in stateless components, We’re better able to create a React Component tree, that’s easy to read, and understand/reuse the code.

2 Likes