React Lifecycle Methods for class and function based components

Software development Company

Musharraf Ali Khan

Software development Company

What are lifecycle methods ?

Lifecycle methods in React components play a crucial role at certain phases when :

  • The components mount i.e created in the DOM.
  • When the props or states of a react component is changed or updated inside the DOM.
  • The components are unmounted or removed from the DOM.

These lifecycle methods provide functionalities to capture and change data inside the DOM and hence, the related behavior at various stages of React components.

Lifecycle methods for Class Components in React :

1. componentDidMount method : This method inside a React Class component is called whenever a React component is mounted or created inside the DOM. We can perform the initial data for rendering with the component when it appears in the beginning inside a DOM.

componentDidMount = () => {
    this.willFocusSubscription = this.props.navigation.addListener(
      "focus",
      async () => {
        let userInfo = await getObjectData("userDetails");
       
        this.setState({
          userData: userInfo
        });
        this.fetchNotifications();
        this.getNotificationCount();
      }
    );
    this.willFocusSubscription = this.props.navigation.addListener(
      "blur",
      () => {
        this.UpdateState();
      }
    );
  };

2. componentDidUpdate method: This method is called whenever a prop or data related to the React component gets updated or changed. This method is called for dynamic rendering of data of a React component.

componentDidUpdate = (prevProps, prevState) => {
    if(prevState.clicked != this.state.clicked) {
      console.log('state changed')
    }
  }

3. componentWillUnmount method : This method is called when a component is unmount or removed from DOM and is useful when we want to remove the related states, props, events, etc. to the component.

componentWillUnmount = () => {
    this.UpdateState()
  }

  UpdateState = () => {
    this.setState({
      userData: {},
      notifications: [],
      pageLoader: false
    });
  }

Lifecycle methods for Function Based Components :

In Function based components for react we do not have these different methods for capturing various lifecycle phases of react but functional components provide us ‘Hooks’ like useState, useEffect, useRef, etc. which provides the same related functionalities as with class components in React.

Here we'll discuss how useEffect hook will provide the functionality of lifecycle methods in function based components in React :

1. componentDidMount functionality with useEffect() : useEffect hook contains two arguments i.e its callback function and array argument and this second array argument plays crucial role in defining the lifecycle phase in function component, if left blank useEffect is called only when the component is mounted inside DOM.

useEffect(() => {
    getProposalList();
    getFirmClients();
  }, []);

In the above code block we can notice that the second array argument is left blank indicating that the code block in callback of useEffect is executed once when the component mounts inside the DOM.

**2. componentDidUpdate with useEffect() : ** If the second array argument contains a reference to a prop or state of the React component then the functionalities inside the callback of useEffect hook are executed whenever the referenced prop or state inside the array is changed.

useEffect(() => {
    if (showForm) {
      setPreviewData();
    }
  }, [showForm]);

In the above code block the second argument array consists of a state name inside it representing that the callback functionalities of useEffect will be executed when the state value is changed when the component is rendered inside the DOM, hence will capture any data manipulation for that state.

**3. componentWillUnmount with useEffect() : ** When a function IS returned from useEffect callback this function is only executed when the component is unmounted or removed from DOM. The return statement inside useEffect will behave like the componentWillUnmount method of the class component.

useEffect(() => {
    getProposalList();
    getFirmClients();
    return () => {
      console.log('Code block to execute when component unmount')
    }
  }, []);

In the above code block you can notice the return statement inside the useEffect callback this represents that the code written inside the function returned from useEffect callback will be executed when the component is unmounted or removed from the DOM. This functionality is mainly used for removing timeOut or interval events or data which may persist even after the component is removed from the DOM.

Conclusion :

On the basis of above comparisons and related behaviors of Class and Function based components in React we can see that lifecycle methods can be used in both of them easily.

Class based components have well defined methods i.e componentDidMount, componentDidUpdate and componentWillUnmount for handling these lifecycle phases in react for data manipulation and code usage.

With increase in the use of more function based components and the use of hooks in them they provide more efficiency and flexibility in the use of these lifecycle methods for various related data manipulations inside these components. We can see that in function based components these lifecycle methods are more easily carried out by use of single useEffect hook. But whether to use class based or function based components in React is still a topic of debate and depends totally on their usage by the developer.

Software development Company
Musharraf Ali Khan

Musharraf Ali Khan is a full stack developer, working at Sofyrus Technologies, have worked on various Web and Mobile based applications, having skills in technologies like React, React Native, Node.JS, Nest.JS .

agile software development company

Contact Us

We’re looking forward to hear from you! Let’s make the next big product together.

Software Development Company in Aligarh

India

B3, HK Compound, NH 509, Sikandarpur, Chherat, Uttar Pradesh 202002

Phone +91 9045708272

Email: [email protected]

Software Development Company in UK

UK

16 Maryatt Avenue, London, U.K.

+447342893185

[email protected]

Software Development Company in Australia

Riyadh

AlSulymaniah - Prince Mamdouh Street AlSafwa Building, Gate 1

+966-597 238 206

[email protected]

Sofyrus Technologies Company
Startup India
Good Firms
MicroSoft for Startup
ISO

© 2019-2023 Sofyrus Technologies | All Right Reserved |