<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ lifecycle methods - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ lifecycle methods - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:25:06 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/lifecycle-methods/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Do Open Source Software Lifecycles Work? ]]>
                </title>
                <description>
                    <![CDATA[ Software projects follow identifiable milestones as they move towards a successful completion. If you want to give your project the best chances of success, it's important to understand what those milestones mean and how they're defined. This article... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-open-source-software-lifecycles/</link>
                <guid isPermaLink="false">66b99657c39234149cf0110b</guid>
                
                    <category>
                        <![CDATA[ lifecycle methods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Clinton ]]>
                </dc:creator>
                <pubDate>Tue, 26 Mar 2024 17:01:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/danial-igdery-FCHlYvR5gJI-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Software projects follow identifiable milestones as they move towards a successful completion. If you want to give your project the best chances of success, it's important to understand what those milestones mean and how they're defined.</p>
<p>This article comes from my Complete LPI Open Source Essentials Exam Study Guide <a target="_blank" href="https://www.udemy.com/course/complete-lpi-open-source-essentials-exam-study-guide/?referralCode=05B999CE18EF4D6E243C">Udemy course</a> and <a target="_blank" href="https://www.amazon.com/dp/B0CK3Q8DCF">book</a>. You can also <a target="_blank" href="https://youtu.be/eZ_4DLVxs7Q">view the video version</a>.</p>
<h2 id="heading-what-are-software-releases">What are Software Releases?</h2>
<p>There are several types of software releases and some related versioning methods used to keep track of software changes and to communicate them to users. We'll start with releases.</p>
<ul>
<li>There's the <strong>alpha release</strong> – an initial version of software that is typically not feature-complete and is not intended for use by the general public. It is used for testing and internal use only. </li>
<li>A <strong>beta release</strong> is a pre-release version of software that is feature-complete but may still have bugs or other issues. It is released to a limited audience for testing and feedback before the final release. </li>
<li>Next will be a <strong>release candidate</strong>, which is a version of software that is considered stable and ready for release, pending final testing and bug fixes. </li>
<li>And finally you'll produce a <strong>general availability release</strong> as the final version of software that's released to the general public.</li>
</ul>
<h2 id="heading-what-is-software-versioning">What is Software Versioning?</h2>
<p>Software versioning (sometimes known as semantic versioning) is the practice of assigning unique version numbers to different releases of software. </p>
<p>Here's a useful example:</p>
<pre><code>vmlinuz<span class="hljs-number">-5.19</span><span class="hljs-number">.0</span><span class="hljs-number">-40</span>-generic
</code></pre><p>In some approaches, the first number in the version number ("5" in this case) is the major version. A major version change indicates significant changes or new features that are not backward compatible with previous versions. </p>
<p>The second number ("19") is the minor version. A minor version change indicates new features or functionality that are backward compatible with previous versions.</p>
<p>The third number in the version number ("0") is the patch version. A patch version change indicates bug fixes or minor changes that are backward compatible with previous versions.</p>
<p>Why distinguish between major and minor releases? Major releases are typically used for significant changes or new features that are not backward compatible with previous versions. Major releases are usually announced to users and customers with a lot of fanfare, as they represent a significant milestone in the development of the software.</p>
<p>Minor releases, on the other hand, are used for smaller changes or new features that are backward compatible with previous versions. Minor releases are typically released more frequently and are intended to provide users with incremental improvements to the software.</p>
<h2 id="heading-what-does-backward-compatibility-mean">What Does Backward Compatibility Mean?</h2>
<p>Backward compatibility is the ability of a newer version of software or system to work with files, data, and other components created in an older version of that software or system. This means that users can upgrade to the newer version without losing access to their existing data or files.</p>
<p>For example, let's assume a user has created a document in an older version of a word processing program. If the newer version of the program is backward compatible, the user can open and edit the same document without any issues. This is because the newer version of the program is designed to read and interpret the file format used in the older version. </p>
<p>However, if the newer version of the program is not backward compatible, the user may not be able to open or edit the file created in the older version without first converting or re-creating it in the newer version. This can be a significant inconvenience for users and can lead to compatibility issues and data loss.</p>
<p>Here are some more quick – but important – definitions.</p>
<h2 id="heading-feature-freeze">Feature Freeze</h2>
<p>Feature freeze is a stage in the software development process where no new features are added to the product or project. It is typically implemented as a deadline by which all new features must be completed and approved before the release of the software product.</p>
<p>The primary goal of a feature freeze is to stabilize the software product in preparation for release. By setting a feature freeze deadline, developers can focus on completing and testing existing features rather than introducing new ones. This allows time for rigorous testing and bug fixing, improving the overall quality and reliability of the software product.</p>
<h2 id="heading-roadmaps">Roadmaps</h2>
<p>A roadmap is a high-level strategic document that outlines the goals, objectives, and timeline for a software product's development. It provides a visual representation of the product development plan, outlining key milestones and the expected timeline for completion. </p>
<p>Roadmaps are useful for communicating the overall direction of a software product to stakeholders, including developers, product managers, investors, and customers.</p>
<h2 id="heading-milestones">Milestones</h2>
<p>Milestones are specific, measurable achievements that mark progress towards the completion of a software product. They're typically set at regular intervals throughout the development process and are used to track progress and ensure that the project stays on schedule. </p>
<p>Examples of milestones might include the completion of a specific feature, the successful completion of a testing phase, or the release of a beta version of the software product.</p>
<h2 id="heading-changelog">Changelog</h2>
<p>A changelog is a document that lists the changes made to a software product over time, including bug fixes, new features, and other updates. Changelogs allow developers and other stakeholders to understand what's been updated and when. </p>
<p>Changelogs are particularly useful for software products that are updated frequently or have a large number of contributors.</p>
<h2 id="heading-long-term-support-lts">Long Term Support (LTS)</h2>
<p>Long term support refers to a software version that is designated for longer-term support and maintenance, typically for a period of several years. During this time, the software vendor provides ongoing support, including bug fixes, security updates, and other maintenance activities. </p>
<p>LTS versions are often used in enterprise environments where stability and reliability are critical. In April of each even year, for example, Canonical will release an LTS version of Ubuntu. These versions are normally supported for four or five years.</p>
<h2 id="heading-end-of-life-eol">End of Life (EOL)</h2>
<p>On the other hand, end-of-life refers to a point in time when a software version is no longer supported by the vendor. This means that the vendor will no longer provide updates or fixes for the software, and any security vulnerabilities or bugs that are discovered will not be addressed. This can leave users with unsupported software that may be prone to security risks and other issues.</p>
<p>When a software product reaches its end-of-life, it is typically retired, and users are encouraged to upgrade to a newer version or switch to a different product. The EOL process is often gradual, with the vendor providing advance notice and guidance to users to help them migrate to a new version or product.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You've seen how it's important to understand the stages through which successful software projects will move. And this isn't just theoretical, because this knowledge gives you the tools to track your progress and quickly identify when things are going off rails.</p>
<p><em>This article comes from my</em> <a target="_blank" href="https://www.udemy.com/course/complete-lpi-open-source-essentials-exam-study-guide/?referralCode=05B999CE18EF4D6E243C"><em>Complete LPI</em></a> Open Source <em>Essentials Study Guide course__.</em> <em>And there's much more technology goodness available at <a target="_blank" href="https://bootstrap-it.com/">bootstrap-it.com</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Lifecycle Methods and Hooks – a Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ React is all about building user interfaces. And to do that effectively, React provides ways for components to manage their lifecycles. This means that components can perform specific tasks at different stages of their existence, from the moment they... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-lifecycle-methods-and-hooks-for-beginners/</link>
                <guid isPermaLink="false">66d45e08680e33282da25e59</guid>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lifecycle methods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Casmir Onyekani ]]>
                </dc:creator>
                <pubDate>Mon, 02 Oct 2023 17:22:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/lifecycle.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://www.freecodecamp.org/news/react-beginner-handbook/#howmuchjavascriptyouneedtoknowtousereact">React</a> is all about building user interfaces. And to do that effectively, React provides ways for components to manage their lifecycles.</p>
<p>This means that components can perform specific tasks at different stages of their existence, from the moment they are created to the point they are removed from the user interface.</p>
<p>Lifecycle methods have been a fundamental part of React for many years. But with the introduction of hooks, React's approach to managing state and side effects in functional components has become more intuitive and flexible.</p>
<p>Just a quick note: although hooks generally replace class components, there are no plans to remove classes from React.</p>
<h3 id="heading-why-this-guide">Why This Guide?</h3>
<p>In this tutorial, you will learn about class component lifecycle methods such as <code>componentDidMount</code>, <code>componentDidUpdate</code>, <code>componentWillUnmount</code>, and <code>shouldComponentUpdate</code>.</p>
<p>You'll also explore React hooks like <code>useState</code>, <code>useEffect</code>, and <code>useContext</code>, and understand why they were introduced. This will make your React journey smoother and more enjoyable.</p>
<p>Whether you're just getting started with React or looking to deepen your understanding, this guide will equip you with the knowledge you need to build responsive and interactive web applications using React's powerful tools.</p>
<p>Let's dive in and uncover the magic of React lifecycle methods and hooks.</p>
<h2 id="heading-how-the-component-lifecycle-works">How the Component Lifecycle Works</h2>
<p>In React, components go through a lifecycle composed of distinct stages. Each of these stages offers specific methods that you can customize to run code at various moments during a component's existence.</p>
<p>These methods help you perform tasks such as initializing data, managing updates, and tidying up resources as needed.</p>
<h3 id="heading-class-component-lifecycle-methods">Class Component Lifecycle Methods</h3>
<p>Let's start by looking at the class component lifecycle methods. These were the primary way to manage component lifecycle before the introduction of hooks.</p>
<h4 id="heading-how-to-use-componentdidmount">How to use <code>componentDidMount</code>:</h4>
<p>This is called after a component has been inserted into the DOM. It's a great place to perform initial setup tasks, like fetching data from an API or setting up event listeners.</p>
<p>Code example:</p>
<pre><code class="lang-jsx">
<span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">data</span>: <span class="hljs-literal">null</span>,
    };
  }

  componentDidMount() {
    <span class="hljs-comment">// This is where you can perform initial setup.</span>

    <span class="hljs-comment">// In this example, we simulate fetching data from an API after the             component has mounted.</span>
    <span class="hljs-comment">// We use a setTimeout to mimic an asynchronous operation.</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> fetchedData = <span class="hljs-string">'This data was fetched after mounting.'</span>;
      <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">data</span>: fetchedData });
    }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulate a 2-second delay</span>
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>componentDidMount Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        {this.state.data ? (
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Data: {this.state.data}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        ) : (
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading data...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        )}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we created a class component called <code>MyComponent</code>. In the constructor, the component's state is initialized with data set to null, and we use it to store the fetched data.</p>
<p>In the <code>componentDidMount</code> method, we simulate fetching data from an API using <code>setTimeout</code> to mimic an asynchronous operation. After 2 seconds (2000 milliseconds), the component's state updates with the fetched data.</p>
<p>In the render method, content is conditionally rendered based on the data state. If data is null, a <code>Loading data...</code> message is displayed. Otherwise, the fetched data is displayed.</p>
<p>When you use this component in your application, you'll notice that the Loading data... message is shown initially, and after 2 seconds, the fetched data is displayed. This demonstrates how <code>componentDidMount</code> is useful for performing tasks after a component has been added to the DOM.</p>
<h4 id="heading-how-to-use-componentdidupdateb">How to use <code>componentDidUpdate</code>B:</h4>
<p>This is called after a component has re-rendered due to changes in its state or props. It's a great place to handle side effects or perform additional actions based on those changes.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
    };
  }

  <span class="hljs-comment">// This method will be called when the "Increment" button is clicked</span>
  handleIncrement = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">count</span>: <span class="hljs-built_in">this</span>.state.count + <span class="hljs-number">1</span> });
  };

  <span class="hljs-comment">// componentDidUpdate is called after the component updates</span>
  componentDidUpdate(prevProps, prevState) {
    <span class="hljs-comment">// You can access the previous props and state here</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component updated'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Previous state:'</span>, prevState);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Current state:'</span>, <span class="hljs-built_in">this</span>.state);
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Counter<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleIncrement}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>In this code example, we create a <code>Counter</code> class component with a constructor that initializes the <code>count</code> state to 0. The <code>handleIncrement</code> method updates the count state when the <em>Increment</em> button is clicked.</p>
<p>Inside the <code>componentDidUpdate</code> lifecycle method, we log a message (Component updated) to the console. We also log both the previous state (prevState) and the current state (this.state). This demonstrates how you can access both the previous and current values during an update. The render method displays the current count and a button to increment it.</p>
<p>Now, when you use this <code>Counter</code> component in your application, open the browser's console. Every time you click the <em>Increment</em> button, you'll see messages in the console indicating that the component has updated, along with the previous and current state values.</p>
<p>You can use <code>componentDidUpdate</code> for various purposes, such as making network requests when props or state change, updating the DOM based on state changes, or interacting with third-party libraries after an update. It provides a way to perform actions that should occur specifically after a component has re-rendered.</p>
<h4 id="heading-how-to-use-componentwillunmount">How to use <code>componentWillUnmount</code></h4>
<p>This is called just before a component is removed from the DOM. It's a crucial place to perform cleanup tasks, such as clearing timers, unsubscribing from events, or releasing resources to prevent [memory leaks](https://en.wikipedia.org/wiki/Memory_leak#:~:text=In computer science%2C a memory,longer needed is not released.).</p>
<p>Let's illustrate a simple React component that sets up a timer when it mounts, using <code>componentDidMount</code> method, and clears that timer when it unmounts using the <code>componentWillUnmount</code> method.</p>
<p>Code example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TimerComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">seconds</span>: <span class="hljs-number">0</span>,
    };
    <span class="hljs-built_in">this</span>.timer = <span class="hljs-literal">null</span>; <span class="hljs-comment">// Initialize the timer</span>
  }

  <span class="hljs-comment">// When the component mounts, start the timer</span>
  componentDidMount() {
    <span class="hljs-built_in">this</span>.timer = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">seconds</span>: <span class="hljs-built_in">this</span>.state.seconds + <span class="hljs-number">1</span> });
    }, <span class="hljs-number">1000</span>); <span class="hljs-comment">// Update every 1 second (1000 milliseconds)</span>
  }

  <span class="hljs-comment">// When the component unmounts, clear the timer to prevent memory leaks</span>
  componentWillUnmount() {
    <span class="hljs-built_in">clearInterval</span>(<span class="hljs-built_in">this</span>.timer);
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Timer Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Elapsed Time: {this.state.seconds} seconds<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> TimerComponent;
</code></pre>
<p>In this example, we created the <code>TimerComponent</code> class. Inside the constructor, the component's state is initialized with a seconds property, which we'll use to keep track of the elapsed time. The timer variable is also set to null.</p>
<p>In the <code>componentDidMount</code> lifecycle method, the timer is started by using <code>setInterval</code>. This timer increments the seconds state property every second.</p>
<p>In the <code>componentWillUnmount</code> lifecycle method, the timer is cleared using <code>clearInterval</code> to ensure that it doesn't continue running after the component has been removed from the DOM.</p>
<p>In the render method, the elapsed time is displayed based on the seconds state property.</p>
<p>When you use this <code>TimerComponent</code> in your application and render it, you'll notice that the timer starts when the component is mounted and stops when the component is unmounted. This is thanks to the cleanup performed in the <code>componentWillUnmount</code> method. This prevents resource leaks and ensures that<br>the timer is properly managed throughout the component's lifecycle.</p>
<h4 id="heading-how-to-use-shouldcomponentupdate">How to use <code>shouldComponentUpdate</code></h4>
<p>We use this lifecycle method to control whether a component should re-render when its state or props change. It is particularly useful for optimizing performance by preventing unnecessary renders.</p>
<p>Let's create a simple React class component and use the <code>shouldComponentUpdate</code> method to decide whether the component should re-render based on changes in its state.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    <span class="hljs-comment">// Allow the component to re-render only if the count is even</span>
    <span class="hljs-keyword">if</span> (nextState.count % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// Re-render</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Don't re-render</span>
  }

  incrementCount = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState(<span class="hljs-function">(<span class="hljs-params">prevState</span>) =&gt;</span> ({ <span class="hljs-attr">count</span>: prevState.count + <span class="hljs-number">1</span> }));
  };

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Counter Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.incrementCount}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>In this example, we created the <code>Counter</code> class component that maintains a count state, which starts at 0. In the <code>shouldComponentUpdate</code> method, we check whether the next state's count is even. If it is, we allow the component to re-render. Otherwise, we prevent the re-render.</p>
<p>The <code>incrementCount</code> method is called when the <em>Increment</em> button is clicked. It updates the count state by incrementing it.</p>
<p>In the render method, the current count and a button to increment it is displayed.</p>
<p>If you click the <em>Increment</em> button and the count becomes an odd number, the component won't re-render. This behavior demonstrates how <code>shouldComponentUpdate</code> can be used to optimize rendering in situations where not all state changes should trigger a re-render.</p>
<h2 id="heading-introducing-react-hooks">Introducing React Hooks</h2>
<p>React introduced hooks in version 16.8. They granted functional components access to state and various React features without writing class components.</p>
<p>As a result, class components have become largely unnecessary. Hooks simplify component logic and make it more reusable.</p>
<h3 id="heading-why-use-hooks">Why use Hooks?</h3>
<p>Hooks were introduced to address several issues and make React code easier to understand and maintain:</p>
<ul>
<li><p>Complexity – class components can become complex when managing state and side effects.</p>
</li>
<li><p>Reusability – logic in class components isn't easily shareable between components.</p>
</li>
<li><p>Learning Curve – class components introduce a steeper learning curve for newcomers to React.</p>
</li>
</ul>
<h3 id="heading-commonly-used-react-hooks">Commonly used React Hooks</h3>
<h4 id="heading-the-usestate-hook">The <code>useState</code> hook</h4>
<p><code>useState</code> lets you add state to functional components. It returns an array with the current state value and a function to update it.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, we used the <code>useState</code> hook to manage a counter's state. When the Increment button is clicked, <code>setCount</code> updates the count state, causing the component to re-render with the updated value.</p>
<h4 id="heading-the-useeffect-hook">The <code>useEffect</code> hook</h4>
<p><code>useEffect</code> is used for side effects in functional components, similar to <code>componentDidMount</code> and <code>componentDidUpdate</code>. It runs after rendering and can be controlled by specifying dependencies.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Fetch data from an API</span>
    fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setData(data));
  }, []); <span class="hljs-comment">// Empty dependency array, runs only once</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{data ? data.message : 'Loading...'}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>In this example, <code>useEffect</code> is used to fetch data from an API when the component mounts. The empty dependency array <code>[]</code> ensures that the effect runs only once.<br>When the data is fetched, <code>setData</code> updates the data state, causing a re-render with the fetched information.</p>
<h4 id="heading-the-usecontext-hook">The <code>useContext</code> hook</h4>
<p><code>useContext</code> allows functional components to access context values. It's a way to pass data down the component tree without explicitly passing props.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx">
<span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// Create a context</span>
<span class="hljs-keyword">const</span> MyContext = React.createContext();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> value = useContext(MyContext);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Context Value: {value}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>In this example, we create a context called <code>MyContext</code>. The <code>useContext</code> hook allows <code>MyComponent</code> to access the value stored in this context. It's a powerful tool for managing global state in your application.</p>
<h3 id="heading-benefits-of-custom-hooks">Benefits of custom hooks</h3>
<p>Custom hooks are functions that use hooks internally and can be reused across multiple components. They help encapsulate and share complex logic.</p>
<p>Here's an example of a custom hook called <code>useLocalStorage</code> that simplifies storing and retrieving data in the browser's local storage:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, initialValue</span>) </span>{
  <span class="hljs-comment">// Retrieve the stored value from local storage</span>
  <span class="hljs-keyword">const</span> storedValue = <span class="hljs-built_in">localStorage</span>.getItem(key);

  <span class="hljs-comment">// Initialize the state with the stored value or the initial value</span>
  <span class="hljs-keyword">const</span> [value, setValue] = useState(storedValue || initialValue);

  <span class="hljs-comment">// Update the local storage whenever the state changes</span>
  <span class="hljs-keyword">const</span> setStoredValue = <span class="hljs-function">(<span class="hljs-params">newValue</span>) =&gt;</span> {
    setValue(newValue);
    <span class="hljs-built_in">localStorage</span>.setItem(key, newValue);
  };

  <span class="hljs-keyword">return</span> [value, setStoredValue];
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useLocalStorage;
</code></pre>
<p>In this custom hook, we import <code>useState</code> from React because we'll use it to manage the state. The <code>useLocalStorage</code> function takes two parameters:</p>
<ul>
<li><p><strong>key</strong>: A string representing the key under which the data will be stored in local storage.</p>
</li>
<li><p><code>**initialValue**</code>: The initial value for the state.</p>
</li>
</ul>
<p>Inside the hook, we first attempted to retrieve the stored value from local storage using <code>localStorage.getItem(key)</code>. Then we initialized the state variable value using <code>useState</code>, using the <code>storedValue</code> if it exists or the <code>initialValue</code> if not.</p>
<p>Next, we defined a function <code>setStoredValue</code> that updates both the state and the local storage when called. It sets the new value in local storage using <code>localStorage.setItem(key, newValue)</code>.</p>
<p>Finally, we returned an array <code>[value, setStoredValue]</code> as the hook's return value, allowing components to access the stored value and update it as needed.</p>
<p>Here's an example of how you can use the <code>useLocalStorage</code> hook in a component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> useLocalStorage <span class="hljs-keyword">from</span> <span class="hljs-string">'./useLocalStorage'</span>; <span class="hljs-comment">// Import the custom hook</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Use the custom hook to manage a "username" stored in local storage</span>
  <span class="hljs-keyword">const</span> [username, setUsername] = useLocalStorage(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Guest'</span>);

  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    setUsername(e.target.value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {username}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your username"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this example, we import the <code>useLocalStorage</code> custom hook and use it to manage a username value in local storage. The component initializes the username state using the hook and updates it when the input field changes.</p>
<p>The value is stored and retrieved from local storage, allowing it to persist across page reloads.</p>
<p>Custom hooks are a powerful way to encapsulate and reuse complex logic in React applications, making your code more modular and maintainable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React provides developers with powerful tools to manage the lifecycles of their components. These lifecycles allow components to perform specific tasks at different stages of their existence, from creation to removal.</p>
<p>In this guide, we've explored React's class component lifecycle methods. These methods have been a fundamental part of React for many years and continue to be relevant in certain scenarios.</p>
<p>You've also been introduced to React Hooks. These have become the preferred way to manage state and side effects in React applications. They offer a more intuitive and flexible approach to building components.</p>
<p>While hooks have gained popularity and generally replace the need for class components, it's important to note that there are no plans to remove class components from React. Existing codebases and third-party libraries may still use class components, so understanding both class component lifecycles and hooks is<br>valuable for React developers.</p>
<p>In summary, React's lifecycle methods and hooks are crucial for building dynamic and efficient applications, and they offer developers a range of options to manage component behavior and state. As you continue to explore and work with React,<br>you'll find that having a solid understanding of both lifecycles and hooks will make you a more versatile and capable React developer.</p>
<p>If you found this guide helpful and enjoyable, please give it a like. For more insightful tutorials, follow me on <a target="_blank" href="https://twitter.com/casweb_dev">X</a> for updates 🙏.</p>
<p>Enjoy your coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Component Lifecycle Methods – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In React, components have a lifecycle that consists of different phases. Each phase has a set of lifecycle methods that are called at specific points in the component's lifecycle. These methods allow you to control the component's behavior and perfor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-component-lifecycle-methods/</link>
                <guid isPermaLink="false">66ba612ff4ac8da2b2c2e873</guid>
                
                    <category>
                        <![CDATA[ components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lifecycle methods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ valentine Gatwiri ]]>
                </dc:creator>
                <pubDate>Thu, 25 May 2023 14:28:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-from-2023-05-23-10-50-48.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In React, components have a lifecycle that consists of different phases. Each phase has a set of lifecycle methods that are called at specific points in the component's lifecycle. These methods allow you to control the component's behavior and perform specific actions at different stages of its lifecycle.</p>
<p>A component's lifecycle has three main phases: the Mounting Phase, the Updating Phase, and the Unmounting Phase. </p>
<p>The Mounting Phase begins when a component is first created and inserted into the DOM. The Updating Phase occurs when a component's state or props change. And the Unmounting Phase occurs when a component is removed from the DOM.</p>
<h2 id="heading-component-mounting-phase">Component Mounting Phase</h2>
<p>The mounting phase refers to the period when a component is being created and inserted into the DOM. </p>
<p>During this phase, several lifecycle methods are invoked by React to enable the developer to configure the component, set up any necessary state or event listeners, and perform other initialization tasks.</p>
<p>The mounting phase has three main lifecycle methods that are called in order:</p>
<h3 id="heading-the-constructor-lifecycle-method">The <code>constructor()</code> lifecycle method</h3>
<p>The <code>constructor()</code> method is called when the component is first created. You use it to initialize the component's state and bind methods to the component's instance. Here's an example:</p>
<pre><code><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>
    };
    <span class="hljs-built_in">this</span>.handleClick = <span class="hljs-built_in">this</span>.handleClick.bind(<span class="hljs-built_in">this</span>);
  }

  handleClick() {
    <span class="hljs-built_in">this</span>.setState(<span class="hljs-function"><span class="hljs-params">prevState</span> =&gt;</span> ({
      <span class="hljs-attr">count</span>: prevState.count + <span class="hljs-number">1</span>
    }));
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleClick}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre><p>In this example, the <code>constructor()</code> method sets the initial state of the component to an object with a <code>count</code> property set to <code>0</code>, and binds the <code>handleClick</code> method to the component's instance. The <code>handleClick</code> method increments the <code>count</code> state property when the button is clicked.</p>
<h3 id="heading-the-render-lifecycle-method">The <code>render()</code> lifecycle method</h3>
<p>The <code>render()</code> method is responsible for generating the component's virtual DOM representation based on its current props and state. It is called every time the component needs to be re-rendered, either because its props or state have changed, or because a parent component has been re-rendered.</p>
<p>In the above example in the constructor part:</p>
<pre><code class="lang-jsx">render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleClick}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
</code></pre>
<p> The <code>render</code> method displays the current count value and a button. When the button is clicked, the <code>handleClick</code> method is invoked. This triggers a state update, causing a re-render, and the updated count is displayed.</p>
<h3 id="heading-the-getderivedstatefromprops-lifecycle-method">The <code>getDerivedStateFromProps()</code> lifecycle method</h3>
<p><code>getDerivedStateFromProps()</code> is a lifecycle method available in React 16.3 and later versions that is invoked during the mounting and updating phase of a component.</p>
<p>During the mounting phase, <code>getDerivedStateFromProps()</code> is called after the constructor and before <code>render()</code>. This method is called for every render cycle and provides an opportunity to update the component's state based on changes in props before the initial render.</p>
<p>The signature of <code>getDerivedStateFromProps()</code> is as follows:</p>
<pre><code><span class="hljs-keyword">static</span> getDerivedStateFromProps(props, state)
</code></pre><p>It takes two parameters:</p>
<p><code>props</code>: The updated props for the component.</p>
<p><code>state</code>: The current state of the component.</p>
<p>The method should return an object that represents the updated state of the component, or <code>null</code> if no state update is necessary.</p>
<p>It's important to note that <code>getDerivedStateFromProps()</code> is a static method, which means it does not have access to the <code>this</code> keyword and cannot interact with the component's instance methods or properties.</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"rice"</span>};
  }
  componentDidMount() {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"pizza"</span>})
    }, <span class="hljs-number">1000</span>)
  }
  <span class="hljs-keyword">static</span> getDerivedStateFromProps(props, state) {
    <span class="hljs-keyword">return</span> {<span class="hljs-attr">favoritefood</span>: props.favfod };
  }
   render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Favorite Food is {this.state.favoritefood}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
    );
  }
}
ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre><p>This is a React component named Header that renders an <code>&lt;h1&gt;</code> element with a string that includes the value of <code>this.state.favoritefood</code>.</p>
<p>The component has a constructor that sets the initial state of <code>favoritefood</code> to "rice".</p>
<p>The <code>componentDidMount()</code> method is also defined, which is called when the component is mounted in the DOM. In this method, there's a <code>setTimeout()</code> function that updates the state of <code>favoritefood</code> to "pizza" after 1 second (1000 milliseconds).</p>
<p>The component also has a static <code>getDerivedStateFromProps()</code> method that takes <code>props</code> and <code>state</code> as arguments and returns an object with a key of <code>favoritefood</code> and a value of <code>props.favfod</code>. This method is called during the mounting and updating phase of the component and is used to derive the state from props.</p>
<p>Finally, the component's <code>render()</code> method returns the <code>&lt;h1&gt;</code> element with the value of <code>this.state.favoritefood</code>.When the component is rendered using <code>ReactDOM.render()</code>, it's mounted to the element with an ID of "root".</p>
<h3 id="heading-the-componentdidmount-lifecycle-method">The <code>componentDidMount()</code> lifecycle method</h3>
<p>The <code>componentDidMount()</code> method is called once the component has been mounted into the DOM. It is typically used to set up any necessary event listeners or timers, perform any necessary API calls or data fetching, and perform other initialization tasks that require access to the browser's DOM API. </p>
<p>Here's an example:</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"rice"</span>};
  }
  componentDidMount() {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"pizza"</span>})
    }, <span class="hljs-number">1000</span>)
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Favorite Food is {this.state.favoritefood}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
    );
  }
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre><p>This code defines a React component called <code>Header</code> that extends the <code>React.Component</code> class. The component has a constructor that initializes the component state with a property called <code>favoritefood</code> set to the string "rice".</p>
<p>The component also has a <code>componentDidMount</code> lifecycle method, which is called by React after the component has been mounted (that is, inserted into the DOM). In this method, a <code>setTimeout</code> function is used to delay the execution of a function that updates the <code>favoritefood</code> state property to "pizza" by 1 second.</p>
<p>Finally, the component has a <code>render</code> method that returns a JSX expression containing an <code>h1</code> element with the text "My Favorite Food is" and the current value of the <code>favoritefood</code> state property.</p>
<h2 id="heading-component-updating-phase">Component Updating Phase</h2>
<p>This phase occurs when a component's props or state changes, and the component needs to be updated in the DOM.</p>
<h3 id="heading-the-shouldcomponentupdate-lifecycle-method">The <code>shouldComponentUpdate()</code> lifecycle method</h3>
<p>The <code>shouldComponentUpdate()</code>  method is called before a component is updated. It takes two arguments: <code>nextProps</code> and <code>nextState</code>. 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.</p>
<p>Here's an example of how to use <code>shouldComponentUpdate()</code>:</p>
<pre><code><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">favoriteFood</span>: <span class="hljs-string">'rice'</span> };
  }

  shouldComponentUpdate(nextProps, nextState) {
    <span class="hljs-comment">// Only re-render if the favoriteFood state has changed</span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.state.favoriteFood !== nextState.favoriteFood;
  }

  changeFood = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">favoriteFood</span>: <span class="hljs-string">'Pizza'</span> });
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Favorite Food is {this.state.favoriteFood}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.changeFood}</span>&gt;</span>Change food<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre><p>The above code defines a <code>Header</code> component that displays the user's favorite food and allows the user to change it by clicking a button. The <code>shouldComponentUpdate()</code> method is implemented to only re-render the component if the <code>favoriteFood</code> state has changed, which is a good way to optimize performance.</p>
<p>The code uses ES6 syntax to define the component class and its methods, and imports <code>Component</code> from <code>React</code> to create the class. The <code>ReactDOM.render()</code> function is used to render the Header component to the DOM.</p>
<h3 id="heading-the-componentwillupdate-lifecycle-method">The <code>componentWillUpdate()</code> lifecycle method</h3>
<p><code>componentWillUpdate()</code> is a lifecycle method in React that gets called just before a component's update cycle starts. It receives the next prop and state as arguments and allows you to perform any necessary actions before the component updates. </p>
<p>But this method is not recommended for updating the state, as it can cause an infinite loop of rendering. It is primarily used for tasks such as making API calls, updating the DOM, or preparing the component to receive new data. <code>componentWillUpdate()</code> is often used in conjunction with <code>componentDidUpdate()</code> to handle component updates.</p>
<pre><code><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
  };

  handleClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">count</span>: <span class="hljs-built_in">this</span>.state.count + <span class="hljs-number">1</span> });
  };

  componentWillUpdate(nextProps, nextState) {
    <span class="hljs-keyword">if</span> (nextState.count !== <span class="hljs-built_in">this</span>.state.count) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Count is about to update from <span class="hljs-subst">${<span class="hljs-built_in">this</span>.state.count}</span> to <span class="hljs-subst">${nextState.count}</span>.`</span>);
    }
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleClick}</span>&gt;</span>
          Increment
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">const</span> rootElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>);
ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span></span>, rootElement);
</code></pre><p>In this example, the <code>componentWillUpdate</code> method is called whenever the component is about to update. In this method, we can access the <code>nextProps</code> and <code>nextState</code> arguments to check if there are any changes to the component's state or props. If there are changes, we can perform some actions or log messages before the update happens.</p>
<h3 id="heading-the-componentdidupdate-lifecycle-method">The <code>componentDidUpdate</code> lifecycle method</h3>
<p>The <code>componentDidUpdate()</code> 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's props or state have changed.</p>
<p>Here's an example of how to use the <code>componentDidUpdate()</code> method:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>
    };
  }

  componentDidUpdate(prevProps, prevState) {
    <span class="hljs-keyword">if</span> (prevState.count !== <span class="hljs-built_in">this</span>.state.count) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Count has been updated:'</span>, <span class="hljs-built_in">this</span>.state.count);
    }
  }

  handleClick() {
    <span class="hljs-built_in">this</span>.setState(<span class="hljs-function"><span class="hljs-params">prevState</span> =&gt;</span> ({
      <span class="hljs-attr">count</span>: prevState.count + <span class="hljs-number">1</span>
    }));
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> this.handleClick()}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExampleComponent;
</code></pre>
<p>In this example, the <code>componentDidUpdate()</code> method is used to log a message to the console whenever the <code>count</code> state has been updated. It compares the previous state (<code>prevState.count</code>) with the current state (<code>this.state.count</code>) to check if there was a change.</p>
<p>Whenever the <code>handleClick()</code> method is called, the <code>count</code> state is incremented, triggering a re-render of the component. After the re-render, <code>componentDidUpdate()</code> is called, and it logs the updated count value to the console.</p>
<p>It's important to include a conditional check inside <code>componentDidUpdate()</code> to prevent infinite loops. If you want to update the state based on a prop change, make sure to compare the previous prop (<code>prevProps</code>) with the current prop (<code>this.props</code>) before updating the state.</p>
<p>Remember that <code>componentDidUpdate()</code> is not called during the initial render of the component, only on subsequent updates.</p>
<blockquote>
<p>As of React 16.3, the <code>componentDidUpdate()</code> method can receive two additional arguments: <code>prevProps</code> and <code>prevState</code>. These arguments provide access to the previous props and state values, which can be useful for performing comparisons.   </p>
<p>But if you are using a more recent version of React, you can utilize the <code>useEffect()</code> hook with dependency array to achieve similar functionality.</p>
</blockquote>
<h3 id="heading-the-getsnapshotbeforeupdate-lifecycle-method">The <code>getSnapshotBeforeUpdate</code> lifecycle method</h3>
<p>The <code>getSnapshotBeforeUpdate()</code> method is called just before the component's UI is updated. It allows the component to capture some information about the current state of the UI, such as the scroll position before it changes. This method returns a value that is passed as the third parameter to the <code>componentDidUpdate()</code> method.</p>
<p>Here's an example of how to use <code>getSnapshotBeforeUpdate()</code> to capture the scroll position of a component before it updates:</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"rice"</span>};
  }
  componentDidMount() {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({<span class="hljs-attr">favoritefood</span>: <span class="hljs-string">"pizza"</span>})
    }, <span class="hljs-number">1000</span>)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"div1"</span>).innerHTML =
    <span class="hljs-string">"Before the update, the favorite was "</span> + prevState.favoritefood;
  }
  componentDidUpdate() {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"div2"</span>).innerHTML =
    <span class="hljs-string">"The updated favorite food is "</span> + <span class="hljs-built_in">this</span>.state.favoritefood;
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Favorite Food is {this.state.favoritefood}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"div1"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"div2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre><p>This is a React component called <code>Header</code> that renders a heading and a button that, when clicked, shows the user's favorite food. The component also has a state that keeps track of the favorite food and whether or not to show it.</p>
<p>The <code>constructor</code> method sets the component's initial state, including the default favorite food of "rice" and the <code>showFavFood</code> state variable to <code>false</code>.</p>
<p>The <code>componentDidMount</code> method is called after the component has been mounted to the DOM. In this case, it sets a timeout that will change the favorite food to "pizza" after one second.</p>
<p>The <code>getSnapshotBeforeUpdate</code> method is called right before the component is updated. It checks if the <code>favoriteFood</code> state variable has changed since the last update and returns an object with the previous favorite food if it has. Otherwise, it returns <code>null</code>.</p>
<p>The <code>componentDidUpdate</code> method is called after the component has been updated. It receives the previous props, state, and snapshot as arguments. In this case, it checks if the snapshot is not null and logs the previous favorite food to the console.</p>
<p>In the <code>render</code> method, the component renders a heading that displays the current favorite food state variable. When the button is clicked, the showFavFood state variable is set to <code>true</code> and a paragraph is rendered that displays the current favorite food state variable.</p>
<p>Finally, the <code>ReactDOM.render</code> function is called to render the Header component inside an HTML element with the id of "root".</p>
<h2 id="heading-component-unmounting-phase">Component Unmounting Phase</h2>
<p>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.</p>
<p>During this phase, React performs a series of cleanup operations to ensure that the component and its associated resources are properly disposed of.</p>
<p>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. </p>
<p>This can happen for various reasons, such as when the component is no longer needed, the parent component is re-rendered without including the child component, or when the application is navigating to a different page or view.</p>
<h3 id="heading-the-componentwillunmount-lifecycle-method">The <code>componentWillUnmount()</code> lifecycle method</h3>
<p>During the unmounting phase, React calls the following lifecycle methods in order:</p>
<ul>
<li><code>componentWillUnmount()</code>: 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.</li>
<li>After <code>componentWillUnmount()</code> is called, the component is removed from the DOM and all of its state and props are destroyed.</li>
</ul>
<p>It'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.</p>
<p>Here's an example of how you might use the <code>componentWillUnmount()</code> method to perform cleanup:</p>
<pre><code><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">showChild</span>: <span class="hljs-literal">true</span>,
  };

  handleDelete = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">showChild</span>: <span class="hljs-literal">false</span> });
  };

  render() {
    <span class="hljs-keyword">const</span> { showChild } = <span class="hljs-built_in">this</span>.state;

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {showChild &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">Child</span> /&gt;</span>}
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleDelete}</span>&gt;</span>
          Delete Header
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  componentWillUnmount() {
    alert(<span class="hljs-string">'The component named Child is about to be unmounted.'</span>);
  }

  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
  }
}

<span class="hljs-keyword">const</span> rootElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>);
ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span></span>, rootElement);
</code></pre><p>This is a React component that renders a <code>MyComponent</code> with a <code>Child</code> component that will be conditionally rendered based on the value of <code>showChild</code> state. </p>
<p>When the user clicks the "Delete Header" button, the <code>handleDelete</code> function will be called which will update the <code>showChild</code> state to <code>false</code>. This causes the <code>Child</code> component to unmount and trigger the <code>componentWillUnmount</code> lifecycle method, which will display an alert message.</p>
<p>The <code>MyComponent</code> class extends the <code>Component</code> class provided by React and defines a state variable <code>showChild</code> with an initial value of <code>true</code>. It also defines a function <code>handleDelete</code> that will be called when the user clicks the "Delete Header" button. This function updates the <code>showChild</code> state to <code>false</code>.</p>
<p>In the render method of  <code>MyComponent</code>, the <code>showChild</code> state is used to conditionally render the <code>Child</code> component using the logical <code>&amp;&amp;</code> operator. If <code>showChild</code> is <code>true</code>, the <code>Child</code> component will be rendered. Otherwise, it will not be rendered.</p>
<p>The <code>Child</code> class extends the <code>Component</code> class and defines a <code>componentWillUnmount</code> method that will be called just before the component is unmounted. In this case, it displays an alert message.</p>
<p>Finally, the <code>ReactDOM.render</code> method is called to render the <code>MyComponent</code> component inside the element with the ID "root" in the HTML document.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, React components have a lifecycle consisting of three phases: Mounting, Updating, and Unmounting. Each phase has specific lifecycle methods that are called at different points in the component's lifecycle.</p>
<p>Understanding these lifecycle methods can help developers to control the component's behavior and perform specific actions at different stages of its lifecycle.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to understand a component’s lifecycle methods in ReactJS ]]>
                </title>
                <description>
                    <![CDATA[ By Anchal Nigam In this article, we are going to explore the lifecycle methods of ReactJS. But, before moving ahead to React’s different lifecycle methods, we should understand what it is. As we know, everything in this world follows a cycle (say hum... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-understand-a-components-lifecycle-methods-in-reactjs-e1a609840630/</link>
                <guid isPermaLink="false">66d45d99cc7f04d2549a371a</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lifecycle methods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 18 Mar 2019 16:48:15 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*_drMYY_IEgboMS4RhvC-lQ.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Anchal Nigam</p>
<p>In this article, we are going to explore the lifecycle methods of ReactJS. But, before moving ahead to React’s different lifecycle methods, we should understand what it is.</p>
<p>As we know, everything in this world follows a cycle (say humans or trees). We are born, grow, and then die. Almost everything follows this cycle in its life, and React components do as well. Components are created (mounted on the DOM), grow by updating, and then die (unmount on DOM). This is referred to as <strong>a component lifecycle.</strong></p>
<p>There are different lifecycle methods that React provides at different phases of a component’s life. React automatically calls the responsible method according to the phase in which the component is. These methods give us better control over our component and we can manipulate them using these methods.</p>
<p>At present, we know what lifecycle methods are and why they are important. So what are these different methods? Let’s have a look into them.</p>
<h3 id="heading-lifecycle-methods">Lifecycle Methods</h3>
<p>A component’s lifecycle is broadly classified into four parts:</p>
<ul>
<li><strong>initialization</strong></li>
<li><strong>mounting</strong></li>
<li><strong>updating, and</strong></li>
<li><strong>unmounting</strong>.</li>
</ul>
<p>Let’s discuss the different lifecycle methods that are available at these different phases (i.e., initialization, mounting, updating &amp; unmounting).</p>
<h4 id="heading-initialization"><strong>Initialization</strong></h4>
<p>This is the phase in which the component is going to start its journey by setting up the state (see below) and the props. This is usually done inside the constructor method (see below to understand the initialization phase better).</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Initialize</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
    <span class="hljs-keyword">constructor</span>(props)
    {
    <span class="hljs-comment">// Calling the constructor of</span>
    <span class="hljs-comment">// Parent Class React.Component</span>
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-comment">// initialization process</span>
    <span class="hljs-built_in">this</span>.state = {
       <span class="hljs-attr">date</span> : <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(),
       <span class="hljs-attr">clickedStatus</span>: <span class="hljs-literal">false</span>
     };
}
</code></pre><h4 id="heading-mounting"><strong>Mounting</strong></h4>
<p>The name is self-explanatory. Mounting is the phase in which our React component mounts on the DOM (i.e., is created and inserted into the DOM).</p>
<p>This phase comes onto the scene after the initialization phase is completed. In this phase, our component renders the first time. The methods that are available in this phase are:</p>
<p><strong>1. componentWillMount()</strong></p>
<p>This method is called just before a component mounts on the DOM or the render method is called. After this method, the component gets mounted.</p>
<p>Note: You should not make API calls or any data changes using this.setstate in this method because it is called before the render method. So, nothing can be done with the DOM (i.e. updating the data with API response) as it has not been mounted. Hence, we can’t update the state with the API response.</p>
<p><strong>2. componentDidMount()</strong></p>
<p>This method is called after the component gets mounted on the DOM. Like componentWillMount, it is called once in a lifecycle. Before the execution of this method, the render method is called (i.e., we can access the DOM). We can make API calls and update the state with the API response.</p>
<p>Have a look to understand these mounting methods:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LifeCycle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  componentWillMount() {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component will mount!'</span>)
   }
  componentDidMount() {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component did mount!'</span>)
      <span class="hljs-built_in">this</span>.getList();
   }
  getList=<span class="hljs-function">()=&gt;</span>{
   <span class="hljs-comment">/*** method to make api call***
  }
  render() {
      return (
         &lt;div&gt;
            &lt;h3&gt;Hello mounting methods!&lt;/h3&gt;
         &lt;/div&gt;
      );
   }
}</span>
</code></pre><h4 id="heading-updating"><strong>Updating</strong></h4>
<p>This is the third phase through which our component passes. After the mounting phase where the component has been created, the update phase comes into the scene. This is where component’s state changes and hence, re-rendering takes place.</p>
<p>In this phase, the data of the component (state &amp; props) updates in response to user events like clicking, typing and so on. This results in the re-rendering of the component. The methods that are available in this phase are:</p>
<ol>
<li><strong>shouldComponentUpdate()</strong></li>
</ol>
<p>This method determines whether the component should be updated or not. By default, it returns true. But at some point, if you want to re-render the component on some condition, then shouldComponentUpdate method is the right place.</p>
<p>Suppose, for example, you want to only re-render your component when there is a change in prop — then utilize the power of this method. It receives arguments like nextProps and nextState which help us decide whether to re-render by doing a comparison with the current prop value.</p>
<p><strong>2. componentWillUpdate()</strong></p>
<p>Like other methods, its name is also self-explanatory. It is called before the re-rendering of the component takes place. It is called once after the ‘<strong>shouldComponentUpdate</strong>’ method. If you want to perform some calculation before re-rendering of the component and after updating the state and prop, then this is the best place to do it. Like the ‘shouldComponentUpdate’ method, it also receives arguments like nextProps and nextState.</p>
<p><strong>3. ComponentDidUpdate()</strong></p>
<p>This method is called just after the re-rendering of the component. After the new (updated) component gets updated on the DOM, the ‘<strong>componentDidUpdate</strong>’ method is executed. This method receives arguments like prevProps and prevState.</p>
<p>Have a look to understand the updating methods better:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LifeCycle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
      <span class="hljs-keyword">constructor</span>(props)
      {
        <span class="hljs-built_in">super</span>(props);
         <span class="hljs-built_in">this</span>.state = {
           <span class="hljs-attr">date</span> : <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(),
           <span class="hljs-attr">clickedStatus</span>: <span class="hljs-literal">false</span>,
           <span class="hljs-attr">list</span>:[]
         };
      }
      componentWillMount() {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component will mount!'</span>)
       }
      componentDidMount() {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component did mount!'</span>)
          <span class="hljs-built_in">this</span>.getList();
       }
      getList=<span class="hljs-function">()=&gt;</span>{
       <span class="hljs-comment">/*** method to make api call***
       fetch('https://api.mydomain.com')
          .then(response =&gt; response.json())
          .then(data =&gt; this.setState({ list:data }));
      }
       shouldComponentUpdate(nextProps, nextState){
         return this.state.list!==nextState.list
        }
       componentWillUpdate(nextProps, nextState) {
          console.log('Component will update!');
       }
       componentDidUpdate(prevProps, prevState) {
          console.log('Component did update!')
       }
      render() {
          return (
             &lt;div&gt;
                &lt;h3&gt;Hello Mounting Lifecycle Methods!&lt;/h3&gt;
             &lt;/div&gt;
          );
       }
}</span>
</code></pre><h4 id="heading-unmounting"><strong>Unmounting</strong></h4>
<p>This is the last phase in the component’s lifecycle. As the name clearly suggests, the component gets unmounted from the DOM in this phase. The method that is available in this phase is:</p>
<p><strong>1. componentWillUnmount()</strong></p>
<p>This method is called before the unmounting of the component takes place. Before the removal of the component from the DOM, ‘<strong>componentWillUnMount’</strong> executes. This method denotes the end of the component’s lifecycle.</p>
<p>Here is a flowchart representation of lifecycle methods:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/NpWCjYyzfnJkn7rXwDmyWwK2DqInFJu6-g1O" alt="Image" width="557" height="645" loading="lazy"></p>
<p>That’s all about this important part of the React world — lifecycle methods. I hope you enjoyed reading it.</p>
<p>Thanks!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
