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 email@example.com to let us know what you think.
Same mechanism used in functional components could be used to update state from a button in a class component. The only difference is that, this dot set state is called with an object that contains the state keys to be updated, and the values to change them to. Lines 21 to 27 show a button with an on-click event handler.
This is sent to a callback arrow function that calls this dot set state with an object that has a key of count and a value that increases the current state value of count by one. As with calling the updating method in a function component, calling set state in a class causes a component re-render, the differing algorithm to run and the reconciliation of all the UI that depends on the state. Clicking the button in the browser window shows that the behavior is still the same.
Another way this could be achieved is to define a handler function in the class and call it through the event handler. This will add an extra layer of complexity to the code as the handler function has to be bound to the component changing the context of this. You can see a click handler function is defined as part of the class on lines 15 to 17 of the code. It does exactly the same as the set state called it before.
On line 26, you can see that the on-click event is now past this dot click handler to call the handler function defined with dot by nest chain to the end. You can see the functionality is still the same. The preferred way to do the binding was to bind any functions in the constructor. We can now remove the dot bind this from line 28. Running the code again, shows the functionality is still the same. From here on in, we'll be focusing on function components and hooks. But at least now you know what the legacy code is doing.
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.