skip to Main Content

React – what is a good analogy to wrap my head around Stateful and Stateless Components? I had trouble going through this abstract concept during my bootcamp and I still struggle to comprehend that.
Can you give exact moment when you went – ‘a-ha, that’s the difference!’ ?

I went through several online articles like this.

2

Answers


  1. The difference between stateful and stateless is that one has state, and the other doesn’t. That means the stateful components are keeping track of changing data, while stateless components print out what is given to them via props, or they always render the same thing.

    Stateful component :

    class Main extends Component {
     constructor() {
       super()
       this.state = {
         books: []
       }
     }
     render() {
       return <BooksList books={this.state.books} />;
     }
    }
    

    Stateless component :

    const BooksList = ({books}) => {
     return (
       <ul>
         {books.map(book => {
           return <li>book</li>
         })}
       </ul>
     )
    }
    

    It’s very common to use stateless components when we want to render re-usable components for example <Card>{children}</Card> component which is re-used in lots of places and use stateful components when it’s the main component and should handle application logic and pass props to the stateless components .

    Login or Signup to reply.
  2. As far as I know, this concept of stateful and stateless is from Flutter, the tutorial you mentioned is using class components that of course you can follow, but nowadays, using only function components is more recommended.

    a function component can have zero, one or more state that you declare it and you can initialize it this way:

    const [myState, setMyState] = useState(1); // initialization to 1
    

    Then, each time you use setMyState() to give your state a new value the component rerenders, because this is how we update the value of a state, with its setter function
    that’s it, as simple as that.

    If your component does not have any state (regardless if it is a function or a class), then you can think of it as a stateless component that does not rerender by itself, unless it is using some hooks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search