Mastering the ReactJS Lifecycle with Function-Based Components: A Comprehensive Guide with Practical Examples
Tags: web3, javascript, react, programming
Published: 2023-07-15 19:27:57

**Introduction:**

React is a popular JavaScript library used for building user interfaces. One of the key aspects of React is its lifecycle, which refers to the sequence of events that occur throughout the lifespan of a component. The React lifecycle methods allow you to control the behavior of your components and perform actions at specific points during their existence.

## React Lifecycle in Function-based Components:

**A component's lifecycle has three main phases**: the Mounting Phase, the Updating Phase, and the Unmounting Phase.

**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.**


In function-based components, the lifecycle methods are implemented using React hooks, such as `useEffect` and `useState`. These hooks provide a way to manage component state and perform side effects.


**1. Mounting Phase :**

The mounting phase refers to the period when a component is being created and inserted into the DOM.

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.

   - `useState`: Used to initialize and manage state within the component.
   - `useEffect` with an empty dependency array (`[]`): Similar to `componentDidMount`, it runs after the initial render. This is where you can perform tasks like fetching data, subscribing to events, or setting up timers.

**2. Updating Phase :**

This phase occurs when a component's props or state changes, and the component needs to be updated in the DOM.

   - `useState`: Used to update and manage state within the component.
   - `useEffect` with a dependency array: Similar to `componentDidUpdate`, it runs when the specified dependencies change. This is where you can handle updates to state or props, perform computations, or trigger side effects.

**3. Unmounting Phase :**

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.

During this phase, React performs a series of cleanup operations to ensure that the component and its associated resources are properly disposed of.

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.

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.

   - `useEffect` cleanup function: Similar to `componentWillUnmount`, it runs just before the component is unmounted. This is where you can perform cleanup operations, such as removing event listeners or canceling asynchronous tasks.

By utilizing these hooks, you can mimic the behavior of the traditional lifecycle methods in function-based components. The `useState` hook helps manage state, while the `useEffect` hook allows you to control side effects and perform cleanup actions.

It's important to note that the React lifecycle methods are not strictly one-to-one equivalents in function-based components. Instead, the hooks offer more flexibility and simplicity in managing component behavior and state.

Understanding the React lifecycle and its corresponding hooks is essential for effectively building React applications. It allows you to control component behavior, handle state changes, perform side effects, and ensure proper cleanup.

## _Let's Understand with Detail Code Example :--_

**1. Mounting Phase:**
   This phase occurs when the component is being created and inserted into the DOM.

   Simple Example:
   ```javascript
   import React from 'react';

   function SimpleMountingExample() {
     console.log('Component mounted');

     return (
       <div>
         <h1>Simple Mounting Example</h1>
         <p>Hello, World!</p>
       </div>
     );
   }
   ```

   Explanation:
   In this simple example, the component is mounted when it is initially rendered. The `console.log` statement in the component's body is executed, logging "Component mounted". The JSX is rendered, and the resulting React element is returned.

   Complex Example:
   ```javascript
   import React, { useState, useEffect } from 'react';

   function ComplexMountingExample() {
     const [data, setData] = useState(null);

     useEffect(() => {
       console.log('Component mounted');

       fetchData();

       return () => {
         console.log('Component unmounted');
       };
     }, []);

     const fetchData = async () => {
       const response = await fetch('https://api.example.com/data');
       const jsonData = await response.json();
       setData(jsonData);
     };

     return (
       <div>
         <h1>Complex Mounting Example</h1>
         {data ? (
           <ul>
             {data.map((item) => (
               <li key={item.id}>{item.name}</li>
             ))}
           </ul>
         ) : (
           <p>Loading data...</p>
         )}
       </div>
     );
   }
   ```

   Explanation:
   In this complex example, the component is mounted when it is initially rendered. The `useEffect` hook is used with an empty dependency array to mimic the `componentDidMount` lifecycle method. It executes the callback function, which logs "Component mounted" and fetches data from an API. The cleanup function within `useEffect` will be executed when the component is unmounted, logging "Component unmounted".

**2. Updating Phase:**
   This phase occurs when the component's state or props are updated, causing a re-render.

   Simple Example:
   ```javascript
   import React, { useState } from 'react';

   function SimpleUpdatingExample() {
     const [count, setCount] = useState(0);

     const handleClick = () => {
       setCount(count + 1);
     };

     return (
       <div>
         <h1>Simple Updating Example</h1>
         <p>Count: {count}</p>
         <button onClick={handleClick}>Increment</button>
       </div>
     );
   }
   ```

   Explanation:
   In this simple example, a `count` state variable is defined using the `useState` hook. When the button is clicked, the `handleClick` function updates the `count` state by incrementing it. This triggers a re-render of the component, updating the displayed count.

   Complex Example:
   ```javascript
   import React, { useState, useEffect } from 'react';

   function ComplexUpdatingExample() {
     const [data, setData] = useState([]);

     useEffect(() => {
       fetchData();
     }, []);

     const fetchData = async () => {
       const response = await fetch('https://api.example.com/data');
       const jsonData = await response.json();
       setData(jsonData);
     };

     return (
       <div>
         <h1>Complex Updating Example</h1>
         <ul>
           {data.map((item) => (
             <li key={item.id}>{item.name}</li>
           ))}
         </ul>
       </div>
     );
   }
   ```

   Explanation:
   In this complex example, the component fetches data from an API using the `useEffect` hook with an empty dependency array, mimicking the `componentDidMount` lifecycle method. The fetched data is stored in the `data` state variable. When the state is updated, it triggers a re-render of the component, causing the fetched data to be mapped and displayed in a list.

**3. Unmounting Phase:**
   This phase occurs when the component is being removed from the DOM.

   Simple Example:
   ```javascript
   import React, { useEffect } from 'react';

   function SimpleUnmountingExample() {
     useEffect(() => {
       return () => {
         console.log('Component unmounted');
       };
     }, []);

     return (
       <div>
         <h1>Simple Unmounting Example</h1>
         <p>Component Content</p>
       </div>
     );
   }
   ```

   Explanation:
   In this simple example, the `useEffect` hook is used with an empty dependency array to mimic the `componentWillUnmount` lifecycle method. It returns a cleanup function that will be executed when the component is about to be unmounted. In this case, the cleanup function logs "Component unmounted".

   Complex Example:
   ```javascript
   import React, { useEffect } from 'react';

   function ComplexUnmountingExample() {
     useEffect(() => {
       const timer = setInterval(() => {
         console.log('Interval running...');
       }, 1000);

       return () => {
         clearInterval(timer);
         console.log('Interval cleared');
       };
     }, []);

     return (
       <div>
         <h1>Complex Unmounting Example</h1>
         <p>Component Content</p>
       </div>
     );
   }
   ```

   Explanation:
   In this complex example, the `useEffect` hook sets up an interval timer that logs "Interval running..." every second. The cleanup function returned by `useEffect` clears the interval when the component is about to be unmounted, logging "Interval cleared".

By examining these examples, you can see how function-based components in ReactJS go through the mounting, updating, and unmounting phases. The lifecycle hooks (`useEffect`) and state management hooks (`useState`) allow you to control the behavior and perform actions at different stages of the component's life.

**Conclusion**

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.

Understanding these lifecycle methods can help developers to control the component's behavior and perform specific actions at different stages of its lifecycle.