Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconReact useEffect() Hook: Usage, How and When to Use It

React useEffect() Hook: Usage, How and When to Use It

Last updated:
25th May, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
React useEffect() Hook: Usage, How and When to Use It

Introduction to the useEffect() Hook

useeffect hook a key component. It handles tasks like data fetching, setting up event listeners, or modifying the DOM and allows users to carry out side effects using functional components. It also controls the component lifecycle.

The useeffect hook leverages two arguments, a function and an optional dependency array. The function passed as the first argument is executed post-initial rendering of the component and then again after every update.You can indicate the variables on which an effect depends using the dependency array. A new run of the effect is performed if any of the dependence array’s variables change.

Inherently the useeffect hook was created to tackle challenges faced under the ES6 class components’ lifecycle. However, it has now become one of the core react concepts.

With this brief on what is useeffect in react, let’s now look at its syntax.

Ads of upGrad blog

Basic Syntax of useEffect() Hook

useEffect supports two arguments; the second argument is optional. The syntax is as below:

useEffect(<function>, <dependency>)

The function includes the side-effect logic. It provokes the execution of a callback directly after the DOM update.

The dependency contains an optional array of dependencies of your side-effects, i.e., state and props values. Note that the use effect hook runs callback only if the dependencies have changed during renderings.

The syntax serves the solitary purpose of useEffect(). It lets you place your side-effect logic inside the callback function and then use the dependencies argument to control when you need the side-effect to run.

You can consider the following syntax when implementing useEffect() Hook:

 // import useEffect

import { useEffect } from ‘react’;

function MyComponent() {

  // calls it above the returned JSX 

  // passes two arguments to it i.e. an array and a function

useEffect(() => {

// effect function

return () => {

// cleanup function

};

}, [/* dependency array */]);

// component rendering logic

}

}

Check out our free technology courses to get an edge over the competition. 

Mounting and Unmounting Components with useEffect() Hook

Mounting

The initial stage of a React component’s lifecycle involves creating and inserting components into the DOM. This lifecycle stage of react useeffect includes the componentDidMount lifecycle method, which executes when the component mounts.

Here’s an example of mounting components using useEffect() hook.

componentDidMount() {

  console.log(“The component is successfully mounted”);

  this.setState({

loaded: true

  })

}

In the above example, componentDidMount lets you use setState. So, you can easily set and change the state in the lifecycle method. The corresponding method employs API calls, call remote endpoints, and fetches data.

Unmounting

This react useeffect lifecycle method handles the cleanup in a DOM. It is like a useeffect cleanup function that removes a component from the DOM. It is called unmounting in React. Unmounting uses only one lifecycle method, i.e., componentWillUnmount. It is called when you want to remove a component from the DOM.

componentWillUnmount() {

  console.log(“The component is successfully unmounted”);

}

Using use effect() Hook for Handling State Changes

The useeffect executes after every render. It is also used to run certain codes in acknowledgement of a state change. You can control the time of execution of the effect by passing the second argument in useEffect() Hook. The second argument works as an array of dependencies, i.e., if the corresponding variables are changed, the effect must be re-run. Note that state is one of the variable types.

The following section illustrates an example to explain how the use effect hook handles state changes.

For example, you may want to run a side effect based on a “day” value. Suppose you have a side effect to display a greeting message depending on the value of the day. The value of the day is saved in a state variable.

Whenever you choose a day, the state gets updated. The change in state value lets you update the greeting message. You should pass the state variable to useEffect hook as a subset of the dependency array.

useEffect(() =>

{

  // Side Effect

}, [state]);

In the above example of useeffect react native, the side effect would run if the value of the state variable updates.

Explore our Popular Software Engineering Courses

 

Using useEffect() Hook with APIs and Network Requests

You can use the ‘useEffect()’ hook with APIs and network requests to fetch data from a server and handle errors. Here’s an example of how to use ‘useEffect()’ with an API and handle network errors:

import React, { useState, useEffect } from ‘react’;

function MyComponent() {

  const [data, setData] = useState(null);

  const [error, setError] = useState(null);

  useEffect(() => { 

    async function fetchData() {

      try { 

        const response = await fetch(‘https://api.example.com/data’);

        if (!response.ok) { 

          throw new Error(‘Network response was not ok’);

        }  

        const json = await response.json();

        setData(json);

      } catch (error) {

        setError(error);

      } 

    }  

    fetchData();

  }, []); 

 

  if (error) {

    return <div>Error: {error.message}</div>;

  }

  if (!data) {

    return <div>Loading…</div>;

  }

  return (

    <div>

      <p>{data.message}</p>

    </div>

  );

}

You can modify this example to include any additional functionality you need to handle network requests and API responses.

Advanced useEffect() Hook Techniques

One of the advanced useeffect react native techniques is memorisation. It is an optimisation technique where the output of a function call is cached. Subsequently, the useeffect return function returns it when the same input is fed again.

Another well-known useEffect() Hook technique is the useMemo Hook. It lets you calculate a value and memorise it. Its syntax is:

 import { useMemo } from ‘react’

  const memoizedValue = useMemo(() => computeExpensiveValue(x, y), [x, y])

useEffect() Hook Dependencies

useEffect() Hook dependencies contain a list of dependencies of your side-effect while also comprising state or prop values. The dependencies argument allows you to catch some component lifecycle events like a component gets mounted or a particular state/prop value gets updated. 

The dependencies argument lets you control the time when the side-effect is invoked, irrespective of the component’s rendering cycle.

Conditional Rendering with useEffect() Hook

useEffect Hook allows you to put the conditions within the hook. Here’s an example.

useEffect(() => {

  if (shouldExecute) {

// (list of conditions)

  }

}, [shouldExecute])

You need to mention the mandatory conditions that you want to execute under the shouldExecute function.

use effect() Hook vs ComponentDidMount() and ComponentDidUpdate() 

 useEffect() Hook vs componentDidUpdate():

useEffect() HookcomponentDidUpdate()
useEffect() Hook is executed for three unique React lifecycles. These React lifecycles are componentDidMount, componentDidUpdate, and componentWillUnmount.componentDidUpdate() executes only after a React component is updated.

 

It doesn’t offer the previous React state and props values.It offers the previous React props and state values.
It can be used only in a React functional component.It can only be invoked inside a class component.

useEffect() Hook vs componentDidMount():

useEffect() HookcomponentDidMount()
useEffect is invoked asynchronously after the browser has already painted the screen.componentDidMount is invoked synchronously before the browser displays the screen.
It obtains the value of count when the effect is created. Providing the effect function to useEffect lets it persist around in memory, and here it only knows that the count was 0.The class-based code makes sure the componentDidMount doesn’t have closure over the state. Hence, it only reads the current value.

Common Mistakes and Best Practices with useEffect() Hook.

Common mistakes

1. Not defining dependencies

useEffect runs whenever a component is rendered. Hence, you must define the values that must trigger a re-render. Otherwise, your useEffect function can create performance issues.

2. Not cleaning up after executing the useEffect hook

useEffect may return a cleanup function that executes when the component is unmounted. Not cleaning up after useEffect can create memory leaks and other concerns. So, it is important to use useeffect cleanup function.

3. Using setState in useEffect function without a dependency

If you update the state in useEffect, it triggers another render. This can lead to an infinite loop. To prevent this, you must always define the state variable which you are updating as a dependency in a useEffect hook.

Explore Our Software Development Free Courses

 

Ads of upGrad blog

Best Practices:

  • If you want to use the useEffect hook, make sure only to use one per component. In the case of multiple useEffect hooks, all of them would run whenever a component renders. So, it can create performance issues and unexpected behaviour.
  • Ensure not to use the useEffect hook inside conditions, loops, or nested functions. If you use State inside for loop, then React would create a new state variable every time the loop runs. Thus, it leads to unexpected behaviour.
  • Make sure not to overuse the useEffect hook. They can make your code difficult to read and may influence the performance if used overly.
  • You must only call the useEffect hook from React functions. If you call it from a class component, you will see an error.

Conclusion

It is best to use useeffect in react if you want to easily access the components’ props and state without writing any additional code. It significantly simplifies side effects in components since it makes it easier to execute side effects when the state or prop changes. You can consider the aspects and best practices discussed above to ensure that your React components perform optimally.

Learning demanding software development skills is crucial in the present era. You can equip yourself with these cutting-edge skills by pursuing upGrad’s Master of Science in Computer Science from LJMU. The course makes you an expert software developer by imparting skills like Java, Python and specialisation in related fields. Thoroughly learning the aspects covered in this course helps you to explore job opportunities like javascript developer, software engineer, and backend engineer.

Along with mastering software development skills, upGrad also helps you uplift your career as a full-stack developer through courses like Executive PG Programme in Full Stack Development from IIITB and Full Stack Software Development Bootcamp. These programs provide immersive learning platforms that let candidates acquire demanding full-stack development skills and effectively pave a path to a successful career!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1 The React Hooks, including the useeffect react let the lifecycle methods be written linearly. It renders flowing order, unlike splitting them between related Class Components. After being optimised, React Hooks serve the fastest approach to functional components.

The React Hooks, including the useeffect react let the lifecycle methods be written linearly. It renders flowing order, unlike splitting them between related Class Components. After being optimised, React Hooks serve the fastest approach to functional components.

2 Some common use cases of useEffect Hook are - Addition of an event listener for a button, Performing an action when a prop or state changes, Data retrieval from API when the component mounts, or Cleaning up event listeners whenever the component unmounts.

Some common use cases of useEffect Hook are - Addition of an event listener for a button, Performing an action when a prop or state changes, Data retrieval from API when the component mounts, or Cleaning up event listeners whenever the component unmounts.

3 Along with understanding what is useeffect in react, you must also understand when to use it. You can place useEffect within the component to directly access the count state variable (or any props) from the effect. You can use it if you want to run code that happens during the component's lifecycle rather than on specific DOM events or user interactions.

Along with understanding what is useeffect in react, you must also understand when to use it. You can place useEffect within the component to directly access the count state variable (or any props) from the effect. You can use it if you want to run code that happens during the component's lifecycle rather than on specific DOM events or user interactions.

Explore Free Courses

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas &#038; Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions &#038; Answers For Freshers &#038; Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16879
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas &#038; Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling &#038; Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions &amp; Answers 2024 [For Freshers &amp; Experienced]
44555
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features &#038; Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas &#038; Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon