Transcript for:
React Component Lifecycle Methods

[Music] in this video we learn about life cycle methods that allow developers to incorporate custom logic at various points during the life of a react component let's begin a react application may contain several components all composed together to deliver a comprehensive feature set having said that various components are brought to life at various points of time and as and when needed for instance let's say we have an application where the click of a button renders a list of elements on the UI until the user clicks the button the components representing list items are not mounted into the Dom and when an item is removed that particular component is destroyed and removed from the Dom this means that like us humans react components do go through a defined lifespan of birth life and death this is known as the life cycle of a react component it is also important to note that we are talking about class components for now because they provide a built-in mechanism for customizing Behavior through life cycle methods the reason why this life cycle is important for us to know and learn about is because react provides predefined Milestones during this lifespan where you the developer are allowed to run code these Milestones are known as life cycle methods in a sense there are three main phases in the life of a react component the mounting phase begins when a react component instance is created and ends when it is inserted into the Dom once the component is rendered into the Dom the component goes through the next phase where there are changes to state or props this state is aptly known as the updating phase because the component reenders and updates the last and final phase is the unmounting phase following which the component is removed from the Dom this happens when the data representing a particular component is removed causing react to remove the associated component across these three phases we get multiple life cycle methods that are aimed at customizing the behavior of the component at a macro level so let's try and run through these life cycle methods to understand their significance our first stop is the mounting phase which as I mentioned earlier occurs when a react component instance is created and in inserted into the Dom in this phase we get four opportunities to customize behavior let's begin with the Constructor method which you can use with class components The Constructor is called before the component is mounted into the Dom the typical use of a Constructor is to initialize local state variables and bind class methods such as this example inside this method you need to call Super which is needed because we are subclassing from the component class this is the only life cycle method where you can initialize State using this do state in all other life cycle methods you need to use this do set State Constructors should only be used for initializing State and binding methods since they are called in the render phase where nothing has gone into the Dom in fact if you're using the class Fields declaration syntax as we've been doing so in our examples you can completely avoid using the Constructor at all the next next life cycle hook that we get in the mounting phase is the get derived state from props this is one of those rare life cycle methods which are used only in very special cases this life cycle Hook is used in both the mounting and updating phases and allows you to perform State changes on the basis of data in the props it is important to note that this method is invoked every time a parent component reenders we'll revisit this in the updating phase as well the next life cycle Milestone at this time in the mounting phase is the render method which you familiar with by now the render method specifically is only needed if you're building class components and its purpose is to return react elements this is also the reason why the random method should stay pure and must never modify the state and should always return the same and predictable result following the render method its initial set of contents are inserted into the Dom so imagine you have a component which has to query an API fetch data and render a list on the UI the very first render would not display any list because we have not performed our API query just yet but the component bare as it may be is inserted into the Dom tree this is because we don't want to block the rendering of the component in any way once the Dom insertion is complete the component did Mount life cycle method is immediately invoked this is where you can perform API queries and other side effects which leads to setting the state once the state is set the component rerenders this finishes the initial mounting phase from this point onwards our component is in the Dom as we move to the updating phase the updating phase occurs when we interact with the component and it renders this interaction includes receiving updated data through props or as an update to the state in both both cases the updating phase begins with an invocation to the get derived state from props method when implemented this method allows you to decide whether you want the state to be updated or not based on the changes to data in the props in simple words when this method is called in the mounting phase it can be used to set State variables based on the data in the props the next time this method is called in the updating phase this time around you can compare the data in the state with that in the props and if you want you can update the state this helps you implement State changes that will occur only if the data in the props differs from what it was earlier this is important to understand because every update to the parent component brings about an update to child components as well even if the data in the props continues to be the same however you may not want to update the child component if the data in the props continues to be the same as before and that is where you can use the get derived state from props function after this life cycle method the should component update method can be invoked this function lets you decide if you want the component to reender based on changes to data in state or props as a result Dom reconciliation can be prevented for components if data in the props or state has not changed thereby boosting performance the way this method works is that it lets you implement a comparison between the current value of State variables and props with the updated values that have just come in during the updating phase usually a prop or state update would result in a reender even if the values in that data are exactly the same as before this can be optimized by doing a comparison and returning true if you want a rerender or false if you can save on one in a large application where components are deeply nested this can vastly improve efficiency and performance by preventing several component instances from rendering just because their parent component was refreshed now instead of implementing this method for optimization react also offers something known as a pure component which automates this process a pure component has should component update baked right into its logic and doesn't need to be manually set up as in the case of a component instance it should be noted however that this comparison is shallow and cannot be customized this kind of a component is perfect for simple use cases where components produce predictable results on the basis of simple and shallow comparisons additionally a pure component will prevent its entire subtree from re-rendering for customized Behavior involving complex data structures you should build a component that implements the should component update function with your own custom comparison logic at this point in the updating phase we have decided if you want to render or not if so the rendom method is called which returns a revised set of nodes to be updated in the Dom but right before the changes are updated in the Dom we get to use the get snapshot before update function this function also lets you compare current and previous values in the state and props but this time we have access to Dom nodes before react implements them this means that you can access and update Dom properties using react references so let's say you have a chat window where every mage message comes from an array of messages in the state now as a new message pops in we add it to the end of the array and we want our chat window to scroll automatically so that it displays the bottommost message as it appears this is where the get snapshot before update method comes in handy the code that you see highlighted on this slide runs right before the component is to update so imagine a new message has been added we know this by comparing the previous length of the array name messages with what it is going to be after the update if the array has grown for instance we get access to an element from the Dom using a ref named list ref this is our chat surface the list of messages shown on the UI what we do then is compute the scroll position as it would be after the update has occurred this value is returned from the get snapshot before update function and is made available to the component Date Update function which runs after react implements the changes in the Dom this then actually Scrolls the chat surface as per the value received in the snapshot variable so as we have just observed we are now at a point where the component has just been updated right at this point we get the component did update life cycle method this function is particularly useful when a component needs to decide if it needs to perform side effects such as quaring an API for more data on the basis of change in state or props the important thing to note here is that this method is not invoked on the first render of a component and is only available when a component updates consider an example of a component that queries an API to fetch weather data for a location as the user selects a location it is stored in the main apps State and passed down to the weather widget component using a prop the weather widget component then queries the API and fetches the result when the app loads for the first time no location is selected hence nothing is shown however the weather vidget component is rendered albeit without data and corresponding elements now when the user selects a location the State updates causing the subtree to render again this causes the component did update method to run and this is where we can query and fetch weather data from an API but here's the most important bit of the process the component did update method will run on every single update the this means it will perpetually keep quering the weather API that is why the component did update function provides access to values in the props and state as they were before the update phase this allows us to compare values and decide if we really want to perform the side effect and query the API or not this is how the component did update method can be used for implementing this optimization at this point our updating phase is complete every time the the state and props change the updating phase occurs again and runs through all the life cycle methods that we've discussed this brings us to the last and final phase known as the unmounting phase so let's say we have a list of products in our cart and the user decides to remove an item from the list clicking the remove button updates the array in the state removing the product which causes the list item for that product to be removed from the Dom this is when the unmounting phase occurs this phase offers only one single method known as component will unmount which occurs right before the component instance is destroyed this life cycle method is extremely useful for cleanup such as removing timer instances and detaching unsubscribing from real-time data sources such as when using websockets when a component is removed this lets you free up memory when the component is destroyed and unmounted as you've seen in this video a class component offers Milestones along its life as it goes from creation to destruction these life cycle methods offer incredible opportunities for us to customize behavior and Implement optimizations that can massively improve the performance of your react application but what about function components can we incoporate life cycle methods in function components the answer is yes and no what I mean is yes you do get a somewhat equivalent workflow using the hooks API and no because they're not exactly life cycle methods and require a somewhat different approach and a thought process I hope this video and the Practical examples we walked through helped you gain a better understanding of what react life cycle methods are and how they work if you're looking to enhance your react coding chops look no further than knowled heart with our outcome based immersive learning approach we fundamentally disrupting the way New Age Technologies are learned you'll get to learn practice assess gain insights on your learning and personalize your Learning Journey on our easy to navigate AI powered skill building platform prism stay tuned for more such videos and explore more about how you can equip yourself with immediately demonstratable in demand skills that will help you get job ready and don't forget to subscribe and press the Bell icon to get notified so you don't miss out on our upcoming videos