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

Best Jobs in IT without coding
134253
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers &#038; Experienced [2023]
900303
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers &#038; Experienced [2024]
905056
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5021
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag &#038; Attributes in HTML: Features, Uses, Examples
5133
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5051
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5123
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5057
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions &#038; Answers (Freshers &#038; Experienced)
5138
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

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