Adding State to Class Components
The course is part of this learning path
This module looks at how to add and update state to a variety of different components.
The objectives of this module are to provide you with an understanding of:
- How to add and update state to class and function components
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
Before React version 16.8, state could only be added to class components. Although the advice is to make all new components as function components, there may well be situations where you come across legacy code. In anticipation of this, we'll look at how state was added to the class component. A simple class component has to have a render method that returns the representation of the UI that the component displays. When adding state to a class component, a constructor must be defined and it calls the super method, which in turn calls the component class constructor. If props are to be used in this component, props must be passed to the constructor and the super call. This can be seen on lines six and seven of the code shown. State is initialized in the constructor by setting it as an object that has keys of the name of the states to be set, and their initial value. You can see in the code on line 10 that we have set the count state initially to five. State is accessed in the component by using the this.state.statename notation as shown on line 19 when rendering the value of count held in state. This also rings true when passing the state value as a prop to a sub component as on line 21. The functionality of this class component in the browser is exactly the same as we showed in the example for the function component. In the developer tools in the browser console we see slightly different information than when rendering a function component. Rather than seeing a section on hooks with state values, we see a section called state, and the key value pairs used. The use and effect of state on the countuser component is unchanged. Facebook have said they will never deprecate class components, so there is no need to convert all class components in an older application to function components. That's unless the component is being substantially rewritten.