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
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 :
Stateless component :
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 .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:
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 functionthat’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.