Updating Class in Function 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 email@example.com to let us know what you think.
The same mechanism used in function components could be used to update state from a button in a class component. The only difference is that, this.setState 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 button with an onClick event handler. This is set to a callback arrow function, that calls this.setState 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 functioning component, calling setState in a class causes a component re-render. The diffing 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 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 setState call did before. On line 26 you can see that the onClick event is now passed this .clickHandler to call in a handler function defined with .bind this chained to the end. You can see the functionality is still the same. The preferred way to do binding was to bind any functions in the constructor. We can now remove the .bind this from line 28. Running the code again shows the functionality is still the same. From here on in we'll be focusing components and hooks, but at least now you know what the legacy code is doing.