Skip to main content

Command Palette

Search for a command to run...

LifeCycle Methods in Class vs Functional Component in ReactJS πŸš€πŸš€

Published
β€’4 min readβ€’View as Markdown
LifeCycle Methods in Class vs Functional Component in ReactJS πŸš€πŸš€
J

I am a Software Developer. I write about Javascript, React and 2 others!!

Overview

In this article, we will learn about life cycle methods in class and functional Components present in one of the most popular javascript libraries ReactJS.

What is ReactJS?

ReactJS is an open-source JavaScript library used for building user interfaces. Developed by Facebook, it allows developers to build reusable UI components that can be used across different parts of a web application. ReactJS uses a declarative approach to programming, making it easier to write and maintain code and debug and test applications. Its use of a virtual DOM also makes it highly efficient and fast. ReactJS is often used with other technologies, such as Redux for state management and React Router for handling routing in single-page applications.

Class Components

In ReactJS, a class component is a way to define a component using a JavaScript class. Class components are useful when you need to have more control over the component's behavior, such as when you need to manage a state or use lifecycle methods.

To create a class component, you would define a class that extends React. Component class. For example:

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

Here are some commonly used lifecycle methods in class components:

  1. constructor(props): This is the first method called when a component is created. It is used to initialize the state and bind event handlers.

  2. componentDidMount(): This method is called after the component has been mounted to the DOM. It is commonly used for fetching data or setting up subscriptions.

  3. componentWillUnmount(): This method is called just before the component is removed from the DOM. It is used to clean up any resources used by the component.

  4. shouldComponentUpdate(nextProps, nextState): This method is called before a component is updated. It is used to determine if the component needs to be re-rendered, based on changes to the props or state.

  5. componentDidUpdate(prevProps, prevState): This method is called after a component has been updated. It is commonly used for updating the DOM or fetching new data based on the updated props or state.

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    // Fetch data or set up subscriptions here
  }

  componentWillUnmount() {
    // Clean up any resources used by the component here
  }

  shouldComponentUpdate(nextProps, nextState) {
    // Check if the component needs to be re-rendered here
  }

  componentDidUpdate(prevProps, prevState) {
    // Update the DOM or fetch new data based on updated props or state here
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

Functional Components

Functional components are another type of component in ReactJS that are simpler and more lightweight than class components. They are just JavaScript functions that return a React element. For Example:

import React from 'react';

function MyComponent(props) {
  return (
    <div>
      <p>Hello, {props.name}!</p>
    </div>
  );
}

In this example, the MyComponent the function takes in a props object as an argument and returns a React element, which is a simple div that displays a greeting based on the name prop passed in.

In React functional components, we can use React Hooks to manage state and lifecycle methods. The most commonly used hooks for lifecycle management are useEffect and useLayoutEffect. For Example:

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

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

  useEffect(() => {
    console.log('Component did mount or update');
    return () => {
      console.log('Component will unmount also known as cleanup function');
    };
  }, [count]);

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

In this example, we're using the useEffect hook to log a message to the console when the component mounts or updates, and then return a function that logs another message when the component unmounts.

The useEffect hook takes two arguments: a function that runs when the component mounts or updates, and an array of dependencies that tells React when to re-run the function. In this case, we're telling React to re-run the function whenever the count state variable changes.

Conclusion

Overall, understanding ReactJS lifecycle methods is essential for building complex, robust applications. By using the appropriate lifecycle methods and hooks, we can ensure that our components behave correctly throughout their lifecycle and provide a smooth user experience.

Thanks for reading the article.