Table of Contents

Conclusion

In React, the useEffect is a very useful hook. The useEffect hook is mainly used to ignore or avoid the unwanted side effects of the class components. For example, we may face many unwarranted side effects if we use normal class components for tasks like fetching data from the API endpoints, updating the DOM or Document Object Model, setting up the timers or subscriptions, etc. The life cycle methods must be used to observe the side effects because we know that the render method is too quick to produce the side effect.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Example:

Now let us discuss an example where we will update the title of the document with respect to the current value of the simple counter component. 

Here, we will be using the class component in React in which the current clicked value will be set to 0 clicks after the initial render. We will code this initial section within the method called componentDidMount(), which is executed only once in the component life cycle. 

We will also use a button in our component to update the count state value. So, whenever we click that button, our count state value will be incremented by 1, and it will also update our document’s title. Now, as the count value state changes, we also need to update the document title again, and for that, the same piece of code needs to be written in the componentDidUpdate() method. In class components of React, the method called componentDidMount() is very useful for updating the state values. However, since we need to write the same code in componentDidUpdate() method, it is considered one of the side effects.

componentDidMount(){

    document.title = `We have clicked the button ${this.state.count} times`;

}

componentDidUpdate(){

    document.title = `We have clicked the button ${this.state.count} times`;

}

In the code above, we set up the document’s title within the componentDidMount() and the componentDidUpdate() methods.

Let us discuss another side effect of using the class component in React. 

In the componentDidMount() method, consider setting up a timer that is set in such a way that a string logs in every few seconds (that time will be set within the setInterval). Now, whenever the component is removed from the Document Object Model, the timer will also be cleared. We generally do this removal procedure within the lifecycle method called componentWillUnmount().

Now let us go through the code implementation for this:

componentDidMount(){

    this.interval = setInterval(this.tick, 2000)

}

componentWillUnmount(){

    clearInterval(this.interval)

}

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Let us look at the code implementation when the timer and the counter are merged to form a single component.

componentDidMount(){

    document.title = `We have clicked the button ${this.state.count} times`;

    this.interval = setInterval(this.tick, 2000)

}

componentDidUpdate(){

    document.title = `We have clicked the button ${this.state.count} times`;

    clearInterval(this.interval)

}

So far, we have noticed the side effects of class components, such as how we need to write the same piece of code twice in the two life cycle methods called componentDidMount() and componentDidUpdate() for updating the title of the document. 

We observed the splitting of the code within two different code blocks. We have also seen how we have to write the code related to the timer, setInterval, and clearInterval within the different life cycle methods.

To avoid all these side effects of class components, we need to have an option where the same code need not be repeated, and all the related codes can be grouped together in the block of code. This is where the useEffect Hook comes into the picture. You can perform side effects in functional components using Effect Hooks. It is the replacement for life cycle methods like componentDidMount(), componentDidUpdate(), and componentWillUnmount().

We will now discuss how the useEffect hook in ReactJs is used to mimic the same life cycle methods of the class components through an example.

Example:

First, let us see the code implementation for the component file in class components.

import React, { Component } from 'react'

class ClassCounterComponent extends Component {

    constructor(props){

        super(props)

        this.state = {

            count: 0

        }

    }

componentDidMount(){

    document.title = `We have clicked the button ${this.state.count} times`

}

componentDidUpdate(prevProps, prevState){

    document.title = `We have clicked the button ${this.state.count} times`

}

render() {

    return (

        <div>

            <button onClick = {() => this.setState(

                  { count: this.state.count + 1})}>

                Button clicked {this.state.count} times

            </button>

        </div>

    )

}

export default ClassCounterComponent;

Below is the code implementation for including the component in App.js.

import React from 'react'

import './App.css'

import ClassCounterComponent from './components/classCounterComponent'

function App(){

    return(

        <div className='App'>

        <ClassCounterComponent />

        </div>

    )

}

export default App

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Now, let us implement the same functionality as in the code above; however, we will implement these functionalities using functional components this time. 

First, we need to make a file in our src folder for implementing the code in our functional components. 

Now let us see the code for the file which contains the functional component using ReactJS useEffect hook.

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

function HookCounterComponent() {

    const [count, setCount] = useState(0)

    useEffect(() => {

        document.title = `We have clicked the button ${count} times`

    return (

        <div>

            <button onClick = {() => setCount(count + 1)}>

               Button clicked {count} times </button>

        </div>

    )

}

export default HookCounterComponent

Now let us see the App.js file for the functional component implementation:

import React from 'react'

import './App.css'

import HookCounterComponent from './components/HookCounterComponent'

function App(){

    return(

        <div className='App'>

        <HookCounterComponent />

        </div>

    )

}

export default App

The output will be the same for both cases. 

To view the output, type npm start in your terminal and press enter; it will open your localhost:3000 in your browser, and you will see your React app as shown below):

  • Before clicking the button:

useEffect_Reactjs_1

  • After clicking the button:

useEffect_Reactjs_2.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, we saw how important the useEffect hook is and why we should prefer it over classical life cycle class components. The useEffect hook is extremely useful for accessing the states of the components and for accessing the props; we don't even have to write additional codes for this. In ReactJS, whenever we pass any function within the useEffect hook, the useEffect hook takes it as a function. And whenever the component renders, the useEffect hook executes the function. The useEffect Hook makes applications faster.

For any professional to land a rewarding job in a reputed company, one must have a good grip on the subject and be well acquainted with the latest developments and technology upgrades apart from having good development skills. Enroll yourself in Simplilearn’s Postgraduate Program in Full Stack Web Development to enhance your skills and gain expertise in the web development field. This course will help you master both the frontend and backend with the different types of technologies and tools like AngularMVC and SpringBoot.

You can also check out Skill-Up, a platform where most in-demand courses are available for free and ensure skill development. The SkillUp courses will help you become an expert in different domains of your choice, such as Machine Learning, Artificial Intelligence, business analytics, etc., and improve your job prospects.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449