Introduction
After building numerous projects using only HTML, CSS and Javascript, you find yourself ready to tackle the most popular front-end framework - React.js
There are literally more than 100s of job postings daily for good React developers. So you have a pretty good reason to move from static pages.
And you are met with your first challenge - State.
Explanation
So what is state exactly?
An oversimplification will be - a variable that re-renders(reloads without refreshing) the parent component. That's all it is.
In class component :
In functional component :
And as any other variable, you are free to add whatever you want in it. Some examples in functional component. (they are applicable in class component as well) :
Changing values of state
Unlike variables where we can directly change the value by reassigning, we change values in set using a function called setState and NOT by re-assigning like a variable.
Changing specific values in state
Whenever you initialize a state with an object, most of the time you might want to change a specific value only and not the whole object. How do we achieve it?
We do it by copying the previous data from the state and modify the value using the property name.
Here, I'm using functional component (same can be done in a class component) :
Conclusion
So that is what state is in React and how you can go about initializing, changing and using it.
States are very helpful and "control" the component.
I often share react related content on my twitter so be sure to check it out!
Top comments (0)