React Lifecycle in Functional Components with useEffect

Hello learners, We will explore the lifecycle of a React functional component using the useEffect hook. The useEffect hook is a fundamental part of React's functional component lifecycle. In this blog post, We will understand how it can be leveraged to handle side effects and perform actions at specific points in the component's lifecycle.



1. Introduction to the useEffect Hook:

Syntax:
useEffect(() => {
    
  }, []);

The useEffect hook allows you to perform side effects, such as data fetching, subscriptions, or manually manipulating the DOM, within a functional component. It combines the functionalities of different lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount, into a single declarative API.


2. Executing Effects on Mount (componentDidMount):

To execute an effect only when the component mounts, you can provide an empty dependency array ([]) as the second argument to useEffect. This ensures that the effect is run only once during the initial rendering.

Example:

import React, { useEffect } from 'react';

const MyComponent = () => {
  useEffect(() => {
  
  console.log('Component mounted');
  
  }, []);

  return <div>My Component</div>;
};

3. Executing Effects on Update (componentDidUpdate):
To execute an effect when specific dependencies change, you can include those dependencies in the dependency array. The effect will run whenever any of the dependencies update.

Example:

import React, { useEffect, useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(`Count updated: ${count}`);
    // Perform side effect based on count value
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

In this example, we utilize the useEffect hook with a dependency array containing the 'count' state variable. The effect is triggered whenever the 'count' value changes. We log the updated count value to the console, providing a way to track changes to the count state. This is useful for performing actions or side effects that depend on the updated state value.

If you want to execute a function every time the component updates then don't include the array ([]) as the second argument to useEffect.
useEffect(() = {

console.log("This will execute every time when component updates")
   
  });

4. Cleanup and Unmounting Effects (componentWillUnmount):

The useEffect hook also allows for cleanup when the component unmounts. This can be useful for unsubscribing from event listeners, cancelling network requests, or releasing any resources acquired by the effect.

Example:

import React, { useEffect } from 'react';

const MyComponent = () => {
  useEffect(() => {
    const mouseMoveHandler = (event) => {
      // Handle mouse move event
    };

    window.addEventListener('mousemove', mouseMoveHandler);

    return () => {
      window.removeEventListener('mousemove', mouseMoveHandler);
    };
  }, []);

  return <div>My Component</div>;
};

5. Limiting the Effect to Specific Dependencies:

In some cases, you may want to run the effect only when certain dependencies change. By listing those dependencies in the dependency array, the effect will be skipped if none of the listed dependencies have changed.

Example:

import React, { useEffect, useState } from 'react';

const MyComponent = ({ data }) => {
  const [formattedData, setFormattedData] = useState('');

  useEffect(() => {
    // Perform data formatting
    setFormattedData(formatData(data));
  }, [data]);

  return <div>{formattedData}</div>;
};

Conclusion:

The useEffect hook has simplified the management of side effects and component lifecycle in React functional components. By understanding how to leverage useEffect with dependency arrays, you can control when effects are executed, handle cleanup tasks, and optimize performance by limiting effects to specific dependencies.

Whether it's handling data fetching, subscriptions, or manipulating the DOM, the useEffect hook empowers developers to build robust and dynamic applications with ease. Embrace the power of useEffect in your React functional components and unlock a whole new level of declarative and efficient programming.

- Nishad Shirsat

Comments

Popular post

Tricks which ES6 feature should we use in javascript promises vs async await?

Mastering JavaScript Variable Declarations: A Comprehensive Guide to let, var, and const difference