Saturday, November 16, 2019

React for dummies: React props and state; what the heck are they?

React props and state


Now you decided to learn React, and you know what the components are by now (hopefully).

The next thing you should get familiarized with are props. Yeah right, but what are they exactly?

Well, props is short for properties: in a way you can compare it to variables in JavaScript (or some other programming language). They come in pairs that look like that: name: value.


To take it a bit further, props are like function arguments in JavaScript that we pass into the components. When we pass them to another component, we can do things we need to do with it.

But what is the state then? Well, imagine a cake made of dough and glaze. Like on the photo:

The lower brown part is name - the one that received the value. Dough is usually not particularly tasty, but you need something to carry the glaze. In our case, the glaze is the value of our props.
And what is the state in this story? State is like a pack of  all the 10 cakes in a box. You can add 2 or 6 more pieces of cake to it, or you can remove some pieces. But when you do it, you shouldn't to it directly: the original state of the cake should always be the same. Since we don't want to mess with the original state, we usually make a copy of it and do whatever we like with its copy. It's like, you don't want to test a new flu medicine on your dog, but you find some stray dog and try to see what happens. If you give it to your own dog, you could soon be a petless walker.

So how do we change state without risking the life of our pet?

We use setState() method, which changes our state by changing  the state of a copy of the genuine state. This method takes an object as an argument, and changes it as we wish / set.

We can also think of setState() as a request to update the component, to change the part of it that we want to change.

Now if you want an additional explanation on how to pass the props, check this post out!
Of course, for much more details, refer to reactjs documentation. This is just introduce those new concepts to you in a simple way, and it is up to you to take it from here!

In the next posts I will write about other basic important concepts of React. Please send questions and comments if you have any. Thanks for reading!


No comments:

Post a Comment

Props: how do we pass them?

Props, how do we pass them? Hey people, it's me again. This time I am trying to share some tips on passing the props in React. Last ...