Doni
Doni

Reputation: 65

What is difference between lifecycle method and useEffect hook?

In class Components, we use componentDidMount, componentDidUpdate lifecycle method to update the state. ex)

componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
}

componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
}

It runs after every render(componentDidUpdate) including first render(componentDidMount). In useEffect hook, we can implment this functionality like this

useEffect(() => {
    document.title = `You clicked ${count} times`;
});

Do these 2 methods have the same effect?

I read this section Reactjs.org and I've tried it on React.js vs 16. I think these 2 methods have the same effects.

useEffect(() => {
    document.title = `You clicked ${count} times`;
});

Upvotes: 5

Views: 12701

Answers (2)

Dinesh Kumar
Dinesh Kumar

Reputation: 488

In react when you use class based components you get access to lifecycle methods(like componentDidMount, componentDidUpdat, etc). But when you want use a functional component and also you want to use lifecycle methods, then using useEffect you can implement those lifecycle methods.

And to your question when you are using a class based component you have all the life cycle methods pre-defined and they triggered accordingly, but using useEffect you need to also make it functional according to the lifecycle method you want to implement. See the below example.

//--------Using a class based component.

import React, { Component } from 'react'
export default class SampleComponent extends Component {
  componentDidMount() {
    // code to run on component mount
  }
render() {
    return (<div>foo</div>)
  }
}

//-----------Using a functional component

import React, { useEffect } from 'react'
const SampleComponent = () => {
  useEffect(() => {
    // code to run on component mount
  }, [])
return (<div>foo</div>)
}
export SampleComponent

They are almost same but the big difference comes with the implementation, there(Class based component) you have custom functions for using lifecycle methods, but here(function based component) you implement each of those you are using manually using useEffect. But developers choose functional components over class based because functional components are considered faster than CBC.(45% Faster React Functional Components)

Upvotes: 5

ravibagul91
ravibagul91

Reputation: 20755

Yes, they are same.

Initially lifecycle methods are supported only for class based components.

Functional components are purly stateless components. But in React 16.8, they have added Hooks. Hooks can be used in plcae of state and lifecycle methods.

Yes, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Upvotes: 2

Related Questions