{"id":5080,"date":"2025-03-05T17:01:16","date_gmt":"2025-03-05T11:31:16","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5080"},"modified":"2025-03-05T17:01:17","modified_gmt":"2025-03-05T11:31:17","slug":"from-mounting-to-unmounting-react-class-component-lifecycle","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/from-mounting-to-unmounting-react-class-component-lifecycle\/","title":{"rendered":"From Mounting to Unmounting: React Class Component Lifecycle"},"content":{"rendered":"<p class=\"ql-align-justify\"><span class=\"ql-size-large\">In React, class-based components play a crucial role in managing the rendering, updating, and unmounting of UI components. functional components with hooks are now the preferred way of writing React components.<\/span><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">class-based components in React were the traditional way to define components prior to the introduction of function components and Hooks in React 16.8.Although function components with Hooks are now preferred for their simplicity and flexibility, class components are still widely used in legacy codebases. understanding class components is essential for working with older react project.<\/span><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">The lifecycle of a class-based component in React consists of different phases during which specific methods are called to handle various operations like initialization, rendering, updating, and unmounting.<\/span><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">React speed comes from its two main phases: the render and commit phases. During the render phase, the constructor is invoked first, followed by the render( ) method. In the commit phase, react updates the DOM and then triggers the componenDidMount( ) method.<\/span><\/p>\n<p><\/p>\n<h1><span class=\"ql-size-large\">Phases of a Class-Based Component Lifecycle<\/span><\/h1>\n<h2><span class=\"ql-size-large\">1.Mounting (Creating a component)<\/span><\/h2>\n<h2><span class=\"ql-size-large\">2.Updating (When props or state change)<\/span><\/h2>\n<h2><span class=\"ql-size-large\">3. Unmounting (Cleaning up the component)<\/span><\/h2>\n<p><\/p>\n<p><span class=\"ql-size-large\"><img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2024\/11\/image-1.png\"><\/span><\/p>\n<p><\/p>\n<p><strong class=\"ql-size-huge\">1. Mounting Phase (Component Creation) :<\/strong><\/p>\n<p><span class=\"ql-size-large\">The mounting phase occurs when the component is being created and inserted into the DOM. <\/span><\/p>\n<p><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2024\/11\/drawiomountin1.drawio.png\"><\/p>\n<p><strong class=\"ql-size-huge\">The constructor( ) lifeCycle method<\/strong><\/p>\n<p><span class=\"ql-size-large\">The constructor is the first method called when the component is created. It\u2019s primarily used for: Initializing the component\u2019s state. and bind event handlers, the constructor is the first method invoked when an instance of the component is created.<\/span><\/p>\n<p><strong class=\"ql-size-large\">The constructor function is used to:<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">Initialize local state or any other third-party libraries.<\/span><\/li>\n<li><span class=\"ql-size-large\">Bonding event handlers the instance<\/span><\/li>\n<\/ul>\n<p><strong class=\"ql-size-large\">some points to keep in mind about constructor:<\/strong><\/p>\n<ul>\n<li><strong class=\"ql-size-large\"> <\/strong><span class=\"ql-size-large\">Every component need not include a constructor.<\/span><\/li>\n<li><span class=\"ql-size-large\"> To set property or use &#8220;this&#8221; we need to call super( ) within constructor.<\/span><\/li>\n<\/ul>\n<p><strong class=\"ql-size-large\">Example<\/strong><\/p>\n<pre class=\"ql-syntax\">class mycomponent extends React.Component {\n constructor(props){\nsuper(props):\/\/ALWAYS CALLS super(props) when using class based components to access the super class methods and \nthis.state={\ncount:1\n};\n}\n}\n<\/pre>\n<p><strong class=\"ql-size-huge\">The Render( ) lifecycle method<\/strong><\/p>\n<p><span class=\"ql-size-large\">The render method is responsible to rendering components to DOM based on its current props and state its is called every time when components to be re- render, the Render() method must return the piece of JSX representing the components structure ,This is the method where the components is displayed in browser.<\/span><\/p>\n<p><strong class=\"ql-size-large\">Example<\/strong><\/p>\n<pre class=\"ql-syntax\">render(){\nreturn(\n&lt;div className=\"use-cart\"&gt;\ufeff\n &lt;h1&gt;NAME={this.state.info.name}&lt;\/h1&gt;\n&lt;h2&gt;LOCATION={this.state.info.location}&lt;\/h2&gt;\n&lt;h2&gt;CONTACT={this.state.info.email&lt;\/h2&gt;\n&lt;img className=\"pic\" src={this.state.info.avatar_URL}\/&gt;\n&lt;\/div&gt;\n);\n}\n<\/pre>\n<p><strong class=\"ql-size-huge\">The ComponentDidMount( ) lifecycle method<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">ComponentDidMount( ) method is called immediately after the component is inserted into the DOM , ComponentDidMout( ) is mainly used to set up any necessary event listeners or timers,perform any necessary API calls or data fetching and DOM manipulations ,<\/span><\/li>\n<li><span class=\"ql-size-large\">Fetching Data from an API: componentDidMount() is used to make an HTTP request or API call to fetch data. Since it\u2019s called after the initial render, it ensures that the component has been inserted into the DOM before attempting to fetch data.<\/span><\/li>\n<\/ul>\n<p><strong class=\"ql-size-large\">Example:<\/strong><\/p>\n<pre class=\"ql-syntax ql-align-justify\">import React from \"react\";\nclass UserClass extends React.Component {&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;constructor(props) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\nsuper(props);&nbsp;\n&nbsp;&nbsp;&nbsp;this.state= {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;info:{&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;name: \"FIROJ\",&nbsp;\n&nbsp;&nbsp;location:\"warangle\",&nbsp;\n&nbsp;&nbsp;avatar_url:\"httpvjkjhvc\"&nbsp;\n&nbsp;&nbsp;&nbsp;}}&nbsp;&nbsp;&nbsp;\n&nbsp;async componentDidMount()\n{\nconst data= await fetch(\"https:\/\/api.github.com\/users\/RIYAZ12697\");\nconst json= await data.json();&nbsp;\nconsole.log(json);\n&nbsp;this.setState({&nbsp;&nbsp;info:json&nbsp;});\n}\n&nbsp;render() {&nbsp;\n&nbsp;&nbsp;return(&nbsp;\n&lt;div className=\"user-cart\"&gt;&nbsp;\n&nbsp;&lt;h2&gt; NAME: {this.state.info.name}&lt;\/h2&gt;&nbsp;&nbsp;\n&nbsp;&lt;h2&gt; LOCATION: {this.state.info.location}&lt;\/h2&gt;&nbsp;&nbsp;&nbsp;\n&lt;h2&gt; CONTACT: sshaikriyaz252@gmail.com&lt;\/h2&gt;&nbsp;&nbsp;\n&nbsp;&lt;img className=\"pic\" src={this.state.info.avatar_url}\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/div&gt;&nbsp;&nbsp;&nbsp;&nbsp;);&nbsp;&nbsp;}\n}\nexport default UserClass;\n\n<\/pre>\n<p><strong class=\"ql-size-huge\">Updating phase(When props or state change)<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">This phase occurs whenever there is change to the component&#8217;s props or state during this phase the React re-renders the component to reflect the new state or props.<\/span><\/li>\n<\/ul>\n<h2><strong class=\"ql-size-large\">Triggers for the updating phase:<\/strong><\/h2>\n<ul>\n<li><strong class=\"ql-size-large\">State Changes<\/strong><span class=\"ql-size-large\">: When the component&#8217;s state is updated using this.setState.<\/span><\/li>\n<li><strong class=\"ql-size-large\">Props Changes<\/strong><span class=\"ql-size-large\">: When the parent component passes new props to the child component.<\/span><\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2024\/11\/updatephase1.jpg\"><\/p>\n<p><\/p>\n<p><\/p>\n<p><strong class=\"ql-size-huge\">The&nbsp;shouldComponentUpdate()&nbsp;lifecycle method<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">The&nbsp;shouldComponentUpdate()&nbsp;method is called before a component is updated.<\/span><\/li>\n<li><span class=\"ql-size-large\">It takes two arguments:&nbsp;nextProps&nbsp;and&nbsp;nextState. This method returns a boolean value that determines whether the component should update or not. If this method returns true, the component will update, and if it returns false, the component will not update.The shouldComponentUpdate method provides a way to optimize performance by skipping unnecessary renders.<\/span><\/li>\n<\/ul>\n<p><\/p>\n<p><strong class=\"ql-size-huge\">Example<\/strong><span class=\"ql-size-huge\">:<\/span><\/p>\n<p>shouldComponentUpdate(nextProps, nextState)<\/p>\n<p>{<\/p>\n<p>return nextProps.value !== this.props.value;<\/p>\n<p><strong class=\"ql-size-huge\">The Render( ) lifecycle method<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">The render phase focuses solely on producing the new virtual DOM representation based on updated state or props. The render phase is distinct from the actual DOM updates (known as the commit phase<\/span><\/li>\n<li><span class=\"ql-size-large\">This is the method that is responsible for&nbsp;inserting a Component into the DOM. This is invoked every time a Component\u2019s state\/props is updated.<\/span><\/li>\n<li><span class=\"ql-size-large\">React compares the newly generated virtual DOM tree with the previous one (diffing algorithm).Based on the comparison, React identifies the minimal set of changes needed to update the actual DOM.<\/span><\/li>\n<\/ul>\n<p><span class=\"ql-size-large\"> Example:<\/span><\/p>\n<p>import React { Component } from &#8220;react&#8221;;<\/p>\n<pre class=\"ql-syntax\">class Counter extends Component \n{ \nconstructor(props) \n{\n super(props);\n this.state = { \ncount: 0,\n }; } \nincrement = () =&gt; \n{ \nthis.setState({ count: this.state.count + 1 }); \n}; \nshouldComponentUpdate(nextProps, nextState) \n{ \n return nextState.count % 2 === 0;\n }\n render() { \nconsole.log(\"Render method called!\"); \nreturn ( \n&lt;div&gt; \n&lt;h1&gt;Count: {this.state.count}&lt;\/h1&gt; \n&lt;button onClick={this.increment}&gt;Increment&lt;\/button&gt; &lt;\/div&gt; );\n }\n }\nexport default Counter\n<\/pre>\n<p><strong class=\"ql-size-huge\">The&nbsp;componentDidUpdate()&nbsp;lifecycle method<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">The&nbsp;componentDidUpdate()&nbsp;method is a lifecycle method in React that is called after a component has been updated and re-rendered. It is useful for performing side effects or additional operations when the component&#8217;s props or state have changed.<\/span><\/li>\n<\/ul>\n<p><strong class=\"ql-size-large\"> It allows you to perform side effects, such as<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">Logging.<\/span><\/li>\n<li><span class=\"ql-size-large\">Fetching data based on new props or state.<\/span><\/li>\n<li><span class=\"ql-size-large\">Interacting with the DOM.<\/span><\/li>\n<\/ul>\n<p><strong class=\"ql-size-large\">Key Arguments of componentDidUpdate<\/strong><\/p>\n<p><span class=\"ql-size-large\">When componentDidUpdate is executed, it provides two arguments:<\/span><\/p>\n<ul>\n<li><strong class=\"ql-size-large\">prevProps<\/strong><span class=\"ql-size-large\">: The props the component had before the update.<\/span><\/li>\n<li><strong class=\"ql-size-large\">prevState<\/strong><span class=\"ql-size-large\">: The state the component had before the update.<\/span><\/li>\n<\/ul>\n<p><span class=\"ql-size-large\">This allows you to compare the previous values with the current ones to decide if some action is necessary.<\/span><\/p>\n<p><span class=\"ql-size-large\">Example:<\/span><\/p>\n<pre class=\"ql-syntax\">import React { Component } from \"react\";\n class Counter extends Component { constructor(props) {\n super(props);\n this.state = { \ncount: 0, \n }; } \n increment = () =&gt; {\n this.setState({ count: this.state.count + 1 }); \n}; \ncomponentDidUpdate(prevProps, prevState) \n{ \n if (prevState.count !== this.state.count) { \nconsole.log(`Count changed from ${prevState.count} to ${this.state.count}`); \n} } \nrender() {\n return ( \n&lt;div&gt;\n&lt;h1&gt;Count: {this.state.count} &lt;\/h1&gt;\n&lt;button onclick={this.increment}Increment &lt;\/button&gt;\n&lt;\/div&gt;\n);\n } \n} \nexport default Counter;\n<\/pre>\n<p><strong class=\"ql-size-huge\">Unmounting Phase<\/strong><\/p>\n<ul>\n<li><span class=\"ql-size-large\">The unmounting phase refers to the lifecycle stage when a component is being removed from the DOM (Document Object Model) and is no longer rendered or accessible.<\/span><\/li>\n<li><span class=\"ql-size-large\">During this phase, React performs a series of cleanup operations to ensure that the component and its associated resources are properly disposed of.<\/span><\/li>\n<li><span class=\"ql-size-large\">The unmounting phase is the last stage in the lifecycle of a React component and occurs when the component is being removed from the DOM tree.<\/span><\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2024\/11\/unmouting.drawio.png\"><\/p>\n<p><strong class=\"ql-size-huge\">The&nbsp;componentWillUnmount()&nbsp;lifecycle method<\/strong><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">This method is called just before the component is removed from the DOM. It allows you to perform any necessary cleanup, such as canceling timers, removing event listeners, or clearing any data structures that were set up during the mounting phase.<\/span><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">After&nbsp;componentWillUnmount()&nbsp;is called, the component is removed from the DOM and all of its state and props are destroyed.<\/span><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">It&#8217;s important to note that once a component is unmounted, it cannot be mounted again. If you need to render the component again, you will need to create a new instance of it.<\/span><\/p>\n<p><strong class=\"ql-size-large\">It allows you to clean up resources such as<\/strong><span class=\"ql-size-large\">:<\/span><\/p>\n<ul>\n<li><span class=\"ql-size-large\">Canceling network requests.<\/span><\/li>\n<li><span class=\"ql-size-large\">Clearing timers or intervals.<\/span><\/li>\n<li><span class=\"ql-size-large\">Removing event listeners.<\/span><\/li>\n<li><span class=\"ql-size-large\">Cleaning up subscriptions <\/span><\/li>\n<\/ul>\n<p><span class=\"ql-size-large\">Example:<\/span><\/p>\n<pre class=\"ql-syntax\">import React from \"react\";\nclass UserClass extends React.Component{&nbsp; \n&nbsp; constructor(props){&nbsp; &nbsp; &nbsp;\n super(props);&nbsp;\n &nbsp; this.state={&nbsp; &nbsp;\n &nbsp; info:{&nbsp; &nbsp; \n&nbsp; &nbsp;  name: \"fffff\",&nbsp; \n&nbsp; &nbsp;  location:\"warangle\",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n &nbsp; avatar_url:\"httpvjkjhvc\"&nbsp;\n &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp;\n &nbsp; }&nbsp;\n&nbsp;async componentDidMount(){\nconst data= await fetch(\"https:\/\/api.github.com\/users\/RIYAZ12697\");\nconst json= await data.json();&nbsp;\nconsole.log(json);&nbsp;\n&nbsp;this.setState({&nbsp;\n &nbsp;info:json&nbsp;\n});&nbsp; \nthis.timer =setInterval(()=&gt;\n{&nbsp; console.log(\"nmaste react\");&nbsp;\n},1000);\n}\ncomponentDidUpdate(){&nbsp; \nconsole.log(\"called in update phase\");\n}\ncomponentWillUnmount()\n{&nbsp; \nclearInterval(this.timer)\n}&nbsp; &nbsp;\n render() {&nbsp; &nbsp; \n&nbsp; return(&nbsp; &lt;div className=\"user-cart\"&gt;&nbsp; &nbsp; &nbsp; \n&nbsp; &nbsp;&lt;h2&gt; NAME: {this.state.info.name}&lt;\/h2&gt;&nbsp; \n&nbsp; &lt;h2&gt; LOCATION: {this.state.info.location}&lt;\/h2&gt;&nbsp; &nbsp;\n &lt;h2&gt; CONTACT: sshaikriyaz@gmail.com&lt;\/h2&gt;&nbsp;\n &nbsp;&lt;img className=\"pic\" src={this.state.info.avatar_url}\/&gt;&nbsp; &nbsp; \n  &lt;\/div&gt;&nbsp; &nbsp;\n &nbsp;  );\n&nbsp; &nbsp; }\n&nbsp; &nbsp; }\nexport default UserClass;\n\n<\/pre>\n<p><strong class=\"ql-size-huge\">Conclusion :<\/strong><\/p>\n<p class=\"ql-align-justify\"><span class=\"ql-size-large\">The lifecycle of class-based components in React provides a structured way to manage and respond to different stages of a component&#8217;s existence. From initial rendering to updating and finally unmounting, these lifecycle methods give developers fine-grained control over their components. The lifecycle methods of class-based components remain essential for handling tasks like fetching data, updating the UI based on state or props, and cleaning up before unmounting. Although function components with Hooks are the modern approach, understanding class component lifecycle methods is still crucial for working with older codebases and for a deeper understanding of how React operates.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In React, class-based components play a crucial role in managing the rendering, updating, and unmounting of UI components. functional components with hooks are now the preferred way of writing React components. class-based components in React were the traditional way to define components prior to the introduction of function components and Hooks in React 16.8.Although function<\/p>\n","protected":false},"author":65,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[231,263,356,355,170],"tags":[224,357,223,358],"class_list":{"0":"post-5080","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-article","7":"category-javascript-frameworks","8":"category-new-react","9":"category-react19","10":"category-reactjs","11":"tag-react","12":"tag-react19","13":"tag-reactjs","14":"tag-reactjs19"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5080","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5080"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5080\/revisions"}],"predecessor-version":[{"id":5085,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5080\/revisions\/5085"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5080"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5080"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5080"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}