The much-awaited topic is here — State. Let’s watch the next video to know about it.
So far, you have learned that state is something that is controlled within a component, unlike props, which are controlled by a parent component. Also, a change in state calls the render() method again. render() method is present only inside a class component because a class component extends from the Component class, which acts as the base class. This is the reason why class components are termed ‘stateful’.
This also leads to the conclusion that functional components cannot contain state because they do not extend from the Component base class and, thus, do not have any render() method. This is why they are termed ‘stateless’.
In the console, you saw how the state changes when the user adds the name and phone number inside the input boxes. Now, let’s update the name and phone so that they change as and when a user fills or makes changes in the input boxes.
The way you get to see the state changing for the name and phone number is beautiful. This is what we call a better user experience.
You can commit your code with “Added state in ‘AddSubscriber’ and ‘App’ components” as the commit message. You can view the diff here.
Notes:
State can be maintained inside a class component only.
State is always initialised inside the class constructor.
In case you define the constructor of a class, you need to call the super() method in the first statement of the constructor definition. This method calls the constructor of the parent class.
To set the state, you must always use the setState() method and must never directly manipulate the application’s state. However, setState() should never be called inside the constructor.
Whenever state is changed, the render() method of the class is called again.
Additional Resources: