React had grown pretty big in the last few years since 2013, and I wanted to share a simple and great insight regarding React which is the difference between state and props, and also how it got upgraded during the years until now.
In React and also other modern JavaScript frameworks such as Angular and Vue, the major approach is using Components.
They allow to create a very simple and small unit, which holds a logic of some sort that is responsible for that area and that area alone.
In the end the components are a building blocks to create a mesmerizing website.
But what actually they do?
The short and simple answer is everything!
A component could be a list of contacts which allows the user to interact with it. The component will be responsible to handle every logical operation related with it and off course render it on screen.
If we look for another example at this page we’re currently at, we can relate the bar on the top to be a component which is called ApplicationBar, which is a name that I just came up with, it could be called anything we want ☺
The reason for using components and separate them as much as possible is for re-usability. Like in the bible of all programmers “Design Patterns” which helps us to design our code, with components is to make the application be composed of small components, but something really important is not to make them too small.
That way, when we face errors and want to extend our application to another level or add some features, without destroying anything, we can do that quite simply.
Now that might sound very easy to do, and I’ll let you down on a little secret.
It actually is very simple but also difficult sometimes if misunderstood.
In order to do the best we can when creating components.
A crucial step is understand the Javascript framework which is used, and because of that we’re going today to understand the bread and butter of React application, which is the State and Props of components.
Component, we need talk ..
In react an important subject to understand, is that the application itself is a component which is using another children components, which helps to build the application itself like writing old fashion HTML tags tree.
This allows us to create a tree like hierarchy which parents components talk with it’s children, and pass them data to interact with.
Moreover, because of this hierarchy we can compose any logical and UI component in one small piece, and re-use it wherever we wish to.
Something that I’ve gone though myself, is the art of making a dynamic component. What I mean by that, is making a component to be dynamic for changes in terms of the UI which is colors, position, animations(CSS/SASS) for the properties we pass to him.
That is a art by itself because we can mislead ourselves to make a component to be “dynamic”, but actually we’re making it to be too much specific, so as like in design patterns, it’s something you should be careful with 🙂
Just for the example, one time I’ve tried to make a custom button which used the SASS styling I’ve made. The problem were, that I wanted to use that button in more places, and I added logic inside the component which made it much more complex and too specific to the task.
I realized my mistake when I wanted to use that button in another place, which were a little hard to implement.
In a short manner because we’ve more about it when we will go forward, but in React we have Class component and Functional Component.
There’s a small difference between them and we’re gonna cover that up as well.
What the hell is props?
Props are basically immutable data that a component has.
The props are passed down to a component from his parent.
Immutable means something that is unchangeable, while mutable is something that can be changed.
What use cases could be used for props you ask?
Let’s say we want to pass a callback function to a son component, so when the son component will activate it, we will get alert about it in the parent component and do some functionality related with that event.
The actual function should not be changed in runtime, because there’s only one function that handles that callback.
Other ways could be giving some variables which are constant in their behavior, so the component could display or use them in any way it desires.
The props came from the idea, that the component like a human being, needs to have some kind of properties that define it and it’s behavior.
For example, a human being has a heart, lungs, legs and all other fun stuff inside which aren’t replaceable because they are the core properties in which a human being needs to live, and in the same kind of relationship, that’s the use of props for a component.
I think that the sentence “a picture worth a thousand words” is amazing and due to that, we now going to see a Functional Components example:
As we can see, it quite simple to pass variables to the component, which can be used in this example, to simply display them.
That’s great and all, but what about the cases I need something that can be modified, or variables that are updated in my parent component, and needs to be updated inside my children as well?
Well great question and glad you asked, for that we have something amazing which is called state and we’re gonna cover up on that right now 🙂
Who has my state?
We talked earlier about a human being and it’s organs. Now we’re going to use a more stylish or nicer analogy for this one, lol 🙂
Everyone wear pretty much different clothes all the time, and each clothing item makes us to perceive them in a different manner.
Off course, anyone can change it’s clothing when they buy new clothes or simply want to change them when they need to.
That’s actually the analogy for the state.
The state is like properties for each component which can be modified in runtime, and they create it by themselves.
We can create the state parameters values by creating new values, or even use the values of the props passed down to us from the parent.
The state itself is a JSON object, which can have inner objects, arrays and single variables as needed, and it could look like this:
When we wish to alter the state we can execute the following code inside the component:
Cool thing about the setState, is that we can get a callback that we finished updating the state for any kind of extra functionality we wish to add.
When you wish to use state for a component you need to use class component or other new technique which is called hooks, which we will see later.
For now let’s see a class component for a person:
Class component allows to access component life cycle like componentDidMount and many more, which all are a callback that tells like its name, that the component just gone through an event of some sort.
Today when we develop any React application the ambition is to use Functional Components because they are easy to debug and maintain.
Some might say that they give better performance because of the no use of life cycle callbacks and the stage.
Unfortunately there’s no testing benchmarks which proves so.
But if there’s no state for function component, how can we handle mutable data in a function component?
Because of that, React team has made hooks, which allows use multiple hooks which compensate over Functional Components missing functionalities.
The captain hook way!
Today in React, there’s a motion to use hooks instead of Class components.
The reason for that is again because it easy to debug and maintain Functional Components.
The main hooks are:
- useState(someKindOfValue) — Creates a state of a particular variable inside our component.
- useEffect(() => {}, [stateValue]) — Allows to get events regarding the rendering of the component and it’s life cycle. We can pass the states we create to it. That way when we update a state, the callback we passed to it is called, so we will get update about the state that it had changed.
Also, when the component is created the callback will get called as well.
We will focus on useState, because we can talk a lot about each one.
When calling the useState, we give it a default value for the state parameter.
We can give it anything we wish, like giving a property from the component which passed from the parent component, just as we talked in Class Components.
You can see below, we actually getting 2 parameters back, and you might be wondering what it is.
Basically for each state parameter we create, we Destructure the parameter and the handler which helps us to update the state for that property.
I actually just finished developing my blog using React, and I’ve discovered hooks, and I must say that I love them.
They made my code a lot more simpler, and made everything more easy to debug and maintain.
But we all talked about state and props, and we don’t really understand how they actually work.
So now we’re going to start the theoretical part, so grab your cup of coffee or bear and get ready 🙂
How does it all affect the UI?
The HTML page is described by the DOM as you might already know.
Inside React we have the virtual DOM, which helps to render only the things that needs to be rendered again, and not the entire DOM itself.
But how does he do it you ask? Great question!
When a component changes its state, it triggers to the child components(who received fields from state as a prop) an event to tell them, that they need to render themselves again.
That actually even more tells us, how small our components should be, because if they do, the performance in terms of live rendering of the application itself could sky rocket if doing all of this right.
Its not a easy job to do so, but with age come wisdom ☺
A word of advice
When using props, there’s this kind of behavior that’s making people who start work in react like me, and even the toughest react developers to do something that is called props drilling.
It’s not something by purpose, but it could happen when we rush to things.
To understand what it means in very detailed way, let’s use the following analogy.
Let’s say the youngest child in the family, wish to ask his father for an extra allowance, because he spent all of his money at the gaming store and he needs more.
The parent gives the allowance to the eldest son and by the age hierarchy, it goes to the youngest son.
What happens if one of the children, decide to be mischief or take a little of the money to himself, and tell that instead of 25$ there were 20$, that’s a great income if doing it daily lol.
In that beautiful short story, we understood I hope, that giving props to a component through a chain of components, could be troublesome if something along the way is not handled as it should be.
That’s why, when using props we should be very careful not to add extra functionality or change it, due to causing unimaginable horrors.
How can we overcome such a thing you ask?
Continue reading 🙂
Component and beyond!
I don’t want to keep you wait too much, but I do wish to say that when handling the state and the components, we should be as minimal as possible, to do what the component needs in their area of responsibility.
I do can tell you about something helps you out in writing an overall application state, something like static or global variables, that be used by every components, which you might have guessed, helps out with preventing props drilling.
The huge players in that field are Mobx and Redux.
They help creating a global state like for our application, which we can access it from every component.
Honest disclaimer — I did used Redux and Mobx in Class components, but I haven’t used them with Functional Components and hooks.
So I hope in the future we will see together a new piece about that subject.
They are both a amazing subject to talk about, but if we will do it now this post would be too long, and they deserve a post of their own 🙂
In conclusion
We’ve did (I hope) a great overview in detailed about props and the state of React components, and the type of components we have today.
We also saw the new kid on the block which is React hooks.
Moreover, we talked a little of how to design a React application.
As always, I do hope you enjoyed reading this piece, and if you have any suggestion to improve this article so everyone else will enjoy it and have a better experience, I’ll be very glad to hear 🙂
Thank you again and I wish you a great journey!