Stateful and stateless components (React)

ref – https://programmingwithmosh.com/javascript/stateful-stateless-components-react/

In a component, state is data we import — typically to show the user — that is subject to change.

Here we have a component Pigeon with a state object that has property pigeons. It is simply an array of pigeons that gets displayed in render. We have state, and we can render things from state.

Also called:

Container vs Presentation components
Smart vs Dumb components.

The literal difference 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/Container/Smart component

Stateless/Presentational/Dumb component

Notice the stateless component is written as a function. As cool as state is, you should always aim to make your components as simple and stateless as possible, so different components can be reused like Lego pieces, even if you don’t have immediate plans to reuse a component. The stateful ones should feel lucky to be so!

Structuring components

Aim to have a parent component keep all the information, and pass it down to its children stateless components.

Doesn’t that look and feel so neat? Having a parent component pass data down to its children also assures that if there is any debugging needed regarding state management, we can go to the parent component to see what’s up, instead of checking state in each child component. All the children components have to worry about is receiving the information as props properly.

So presentational components can vary depending on what information it receives. The difference is that a stateful component keeps track of the information itself, instead of just taking it via props and outputting it.

We can also have components that render static state:

Generally, child components render UI and have no state.

Creating reusable component

Create a stateless reusable component like so:

then use it like so: