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.
- [Instructor] Before Reaction version 16.8, state could only be added to class components. Although the advice to make all new components as functional 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 line six and seven of the code shown. State is initialized in the constructor by setting it as an object that has keys at 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 this dot state dot state name 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 effective state on the count user 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 has been substantially rewritten.
Ed is an Outstanding Trainer in Software Development, with a passion for technology and its uses and holding more than 10 years’ experience.
Ed is responsible for delivering QA’s Programming Foundations course using the Eclipse IDE. His skillset extends into the DevOps sphere, where he is able to deliver courses based around Agile/Scrum practices, version control, and CI/CD.