The course is part of this learning path
This module looks at how to work with External Data in React. You’ll be looking at Class Components, Effect Hooks, and how to handle data.
The objectives of this module are to provide you with an understanding of:
- The component lifecycle
- Hooks in React
- How to create restful services
- How to use an Effect Dependency Array
- How to hand errors in data requests
- How to send data
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.
To understand component lifecycles. It's first easy to look at class components. This is because the component lifecycle methods are built into them. We just override their implementation, the class component clock we are showing demonstrates how we can use a class component state and its lifecycle methods to display a ticking clock on the screen. The most obvious five cycle method is the constructor, this a mounting method in the render phase, and it sets up the components props. If it has any, and its initial state, once the initial render has completed. If a component did mount method exists in the class, this will be called. Traditionally, this is where we would have operated on the dome or made calls for external data as a component will have rendered. We could then get data asynchronously and update state when it has been returned. The component did Mount method in our code is used to set an interval running and this calls a method tick every second. Tick updates to time state within new value. This continues while the component is alive and you can see the clock updating in the browser. When a component has updated, if a component did update method exists, this will be executed. This must have pre props as an argument and can obviously have pre-state and snapshot too. Again, this can be used to operate on the dominant mate network calls for data. The advantage here is that you can use a conditional statement based on the previous props, previous state or the snapshot to decide if this needs to happen. If you're going to set state in this method, it must be wrapped in a conditional statement, to prevent an infinite loop. The component did update, method was not required in this application, but we included a blank implementation for completeness. The final life cycle method we're looking at is the component will amount method. If present, this will be called just before the component is completely removed from the dome, it gives us a chance to do any cleanup we need to by unsubscribing, clearing timers and so on. When we come to amounting the class component clock, we would want to clear there interval so the process doesn't continue to hog resources. This is done in the component will amount method shown.