Updating State 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 firstname.lastname@example.org to let us know what you think.
- [Instructor] State is often updated in an application due to some event without user interaction, or an external influence. A really important concept to mention right from the off here is that you should never directly mutate the value of state. If it needs to be updated, this should be done using the updater function defined when state was declared. Why? Calling the updater function triggers a re render of the component that owns the state, the diffing algorithm will detect that the value of state has changed, and then cascade this change down to every component that uses the state value. The only component will obviously re render. But any component that receives the value as part of its props will too. Mutating the value directly by passes this process, and should not be done for this reason. We'll cover events in a lot more detail when we look into inverse Data flow. But for now, it's sufficient for us to know that we can use any of the events from the API as long as we can locate them. This is for JSX interpretation to distinguish them from HTML attributes. Most will work without camel casing, but there'll be a friendly warning on the console if you do this. You can see in the code for the component with state, we have added a button on line 11 that has an onclick event, we supplied the onclick value as a JSX expression. In this case, we define a callback arrow function that calls set come with an argument of count plus one. Clicking on the button in the browser you will see the expected result. The value displayed increases by one. If we inspect the React developer tools, we can see that the value in the hook state increases when the button is clicked. We should also note that the count user component updates its display as the value supplied to it is propped, ie the current state changes when components with state is re rendered using the new value of count.
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.