Many times I have met people who have been programming with React for some time, and who still do not know exactly what is the difference between the ** props ** and the ** state ** of a component. In this post I will try to explain in the most entertaining way possible in which they differ and what properties they have.
I really like an article by Hootsuite on Github in which they say:
The main responsibility of a component is to translate raw data into rich HTML.
Taking this into account, we could say that the props and the state are those data, of which the component will be nourished to render a good HTML.
Then, a component of React could be seen as a machine or "black box" that has an input, the data, and an output, the HTML. We will focus today on the input, the component data.
Now we will see the part of this black box that interests us today. The props and state. First, before we see how they differ, let's see what they have in common:
- Both are triggers to render a component (when there is a change in one of them, the component is rendered again).
- Since React is deterministic, as long as the entry of props and state doesn't change, the result will always be the same.
So what's the difference?
The props (diminutive of properties) of a component are given from the parent component. We can not alter them, here is the key point. When a parent component creates a child component, it can pass some props (properties that child component will have). The son will be able to make use or not of these properties that his father has given him, but he will not be able to modify them.
The state, on the other hand, is equivalent to a snapshot in the time of a component, it is the current state of that component. Because components vary with time due to interactions with the user, queries to other addresses, etc. During the life cycle of a component, if there is any change, this is stored in an object called state.
In summary we could say that "a component manages its own state, but the properties are given by its predecessor".
We could then classify the components in the following way, with state and without state:
Stateless component: It only has the props. It is not very interactive, basically it has the function of
render ()and little else.
- Stateful component: It has both the props and the state. These components are those that interact with the server, react to user events, etc.
I hope this little guide has helped you understand a little better how the ** props ** and the ** state ** of a component work. As a last recommendation, before creating a component stop to think for two seconds if you need state or not, since not putting it will make your web app much faster. Always use the stateless components for visualizations and data formats, and use the stateful components when the component requires some interaction with either client or server.
Claim your page on DEV before someone else does
Level up every day