Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

React useEffect() Hook: Structure, Usage, Examples & Tips

Updated on 31 October, 2024

55.87K+ views
10 min read

In recent times, React has become the most popular JavaScript Library. It has gained a strong community around it due to its robustness and ease of use. React makes it easy to create interactive UIs and smooth user experiences. Enough about React; I am sure you are already aware of it, which is why you’ve landed on this article. Let’s come to the point and discuss today’s topic, react useEffect hook.  

Hooks are a new addition to React 16.8. They let you use the state and other React functionalities without writing an ES6 class for it. Thereby, hooks have made the use of functional components rather easier than class-based components, which has taken the whole community by amazement! Avid developers like you can pick a detailed tutorial on React Native course and hone your expertise in App development.

What is useEffect hook in React? 

useEffect hook is part of React’s Hooks API. The core principle of this hook is to let you perform side effects in your functional components. The useEffect hook is a smooth combination of React’s lifecycle methods like componentDidMount, componentDidUpdate and componentWillUnmount. According to React documentation, the useEffect hook was developed to overcome some challenges posed by the life cycle methods of ES6 class components.  

Sometimes, we want to run some code after the DOM has been updated. It can be anything, showing pop-ups, sending API requests, logging users’ information etc. and such functions don’t require cleanup to be performed. They are just hit-once functions and then we forget about them. Such places are the best examples to use the useEffect hook.  

You can learn more about Mobile App Development course, which has in-depth explanations of the core concepts of React. Let’s now continue on the useEffect, don’t forget to check out the link though.  

The basic syntax is as follows: 

// onMount 
useEffect(() => { 
console.log("I Only run once (When the component gets mounted)") 
}, []); 

Why Choose React Hook?

The useEffect hook is used to manage side effects in functional components including requesting data, changing the DOM, and creating subscriptions or timers. It mimics the lifecycle functions of class-based components. The aim for introducing useEffect Hook is to eliminate the side effects of employing class-based components. 

For example, operations like as changing the DOM, obtaining data from API endpoints, configuring subscriptions or timers, and so on might cause unintended consequences. Because the render function generates side effects too quickly, life cycle techniques must be used to examine them. 

Structure of useEffect Hook in React

The React useEffect hook, a crucial part of React's functional component arsenal, offers a streamlined way to manage side effects. Comprising a distinct structure, it allows developers to incorporate asynchronous operations, data fetching, subscriptions, or any code that requires React useEffect() cleanup. The fundamental syntax involves passing a function and, optionally, an array of dependencies.

useEffect(() => {
 // Side effect logic
 return () => {
 // Cleanup logic
 };
}, [dependency1, dependency2]);

Explanation:

  • The first argument hosts the side effect logic, encapsulated within a function.
  • The second argument, an array of dependencies, dictates when the effect should re-run, preventing unnecessary executions.

useEffect in React.js Example

Imagine a scenario where data fetching is the side effect:

useEffect(() => {
 const fetchData = async () => {
 const result = await axios.get('https://api.example.com/data');
 setData(result.data);
 };
 fetchData();
}, [dependency]);

Significance of Parameters:

  • Effect Function: Holds the code for the side effect, like fetching data or setting up subscriptions.
  • Dependency Array: Governs when the effect should run based on changes in specified dependencies.
  • Cleanup Function: If provided, runs before the next effect or during component unmounting, facilitating cleanup tasks such as unsubscribing.

Mastering the structure and parameters of React useEffect hook empowers developers to handle asynchronous operations with finesse, ensuring efficient and controlled side effects within React functional components.

Basic Usage of useEffect in React

The react useEffect Hook essentially replaces every single lifecycle function that you may run into. 

useEffect(() => { 
// Update the document title using the browser API    document.title = `You clicked ${count} times`;  
}); 

This snippet is based on a counter-example in which we are setting the document title to a custom message, including the number of clicks. Fetching data, setting subscriptions, and manually modifying the DOM in React components are examples of side effects. Whether or not you're used to calling these operations "side effects", you've probably done them before in a component. 

Different Ways to Mimic Lifecycle Methods Using useEffect Hook 

We know that useEffect() is used to cause side effects in functional components, and it can also handle the componentDidMount()componentDidUpdate(), and componentWillUnmount() life-cycle methods of class-based components within functional components. 

1. For componentDidMount

useEffect(()=>{ 
    //You can add your code here for mounting phase of component 
    console.log("Mounting in Functional Component") 
},[]) 
// adding an empty array ensures that the useEffect is only triggered once  
// (when the component mounts) 

2. For componentDidUpdate

useEffect(()=>{ 
    //You can add your code for updating phase of component 
    console.log("Updating in Functional Component") 
},[values]) 

//values triggers re render whenever they are updated in your program, 

//you can add multiple values by separating them by commas 

3. For componentWillUnmount 

useEffect(()=>{ 
    return()=>{ 
    //You can add your code for unmounting phase of component 
    console.log("Functional Component Removed ") 
    } 
},[]) 

What Arguments are Passed to the useEffect Hook?  

useEffect takes two arguments. The first argument passed to useEffect is a function called effect and the second argument (optional) is an array of dependencies. Below is an example. 

import { useEffect } from "react"; 
import { render } from "react-dom"; 
const App = (props) => { 
  useEffect(() => { 
    console.log("Effect ran"); 
  }); //No second Argument 
  return <h1> upGrad! </h1>; 
};  
const root = document.getElementById("root"); 
render(<App />, root); 

The effect runs when the component is mounted, and whether or not it runs on subsequent updates is determined by an array of dependencies passed as the second argument to react useEffect. 

Effects take no parameters, and the useEffect return function returns either a function or undefined. If the useEffect return function returns a function, the returned function is called cleanup. cleanup is run before the effect is reached (to clean up effects from previous renders). If you want to learn more about why and when to clean up, check out the Best React online course. useEffect returns either a function or undefined, so it's not uncommon to see effects that haven't been cleaned up. 

The second argument of useEffect is an array of dependencies. If you want to control when the effect runs after the component has been mounted, pass an array of dependencies as the second argument. Dependencies are values defined outside useEffect but used inside useEffect, such as: 

function App(){ 
 // state 
         const[state, setState] = useState(0); 
         useEffect(() => { 
              console.log(state); 
              // since we are using state, we have to pass it as a dependency 
         }, [state]) 
} 

React will compare the current value of the constraint with the value from the previous render. If they are not equal, the effect is called. This argument is optional. If omitted, the effect will run after each render. You can pass an empty array if you only want the effect to run on the first render. 

useEffect(() => { 
       console.log("Effect ran"); 
}, []) // the useEffect will now only be evoked once per render 

Dependencies can be states or props. Note that values defined inside a component outside of useEffect must be passed as dependencies when used inside useEffect. This is illustrated below. 

function App() { 
     const [count, setCount] = useState(1); 
     // count is defined in App, but outside of useEffect 
     useEffect(() => { 
       //since we are using count, we have to pass it as a dependency 
       console.log(count); 
     }, [count]) 
} 

The output will be the count value and if the count value changes it will be the changed value as we are using count as the dependency. 

Passing a Function as a Dependency

If I define a function outside useEffect and call it inside the effect, should I pass it as a dependency? 

The following is a react useEffect example: 

function App(){ 
    const [data, setData] = useState(null); 
    const fetchData = () => { 
         // some code 
    } 
    useEffect(() => { 
    fetchData(); //used inside useEffect 
     }, [fetchData]) 
} 

It is not recommended to define a function outside and call it inside an effect. In the above case, the passed dependency is a function, and a function is an object, so fetchData is called on every render. React compares the fetchData from the previous render and the current render, but the two aren't the same, so the call is triggered. 

When and How to Use useEffect Hook? 

The useEffect in react js allows you to perform side effects in your components. The react useEffect examples of side effects include retrieving data, direct DOM updates, and timers. The second argument is optional.

useEffect(<function>, <dependency>) 

Now that we are clear with the core concept of the useEffect hook, the question arises of when and how to use this hook. Following are 4 major use-cases where we use the useEffect hook. Before proceeding to the use cases, I would like you to go through a course that will not only help you get through many core concepts of App development but also provide you with the Mobile App Development certification online that adds a shining star to your resume, do check it out.  

1. When Component Mounts

You can make use of the useEffect hook in a similar fashion to what the componentDidMount function did in class-based components. Usually, adding listeners, fetching initial data, etc., are the actions executed when the component is mounting. This is easily achieved by useEffect; the only thing you need to make sure of is that you have to pass the dependency array as empty. If there are no dependencies that means it will remain the same all the time. 

2. On Every Component, Render

To call the useEffect function on every component render, skip adding the dependency list. When the dependency list is not present, react will have nothing to compare the previous value with; as a result, the effect will run every time.  

3. On Every Component, Render with a Condition

To call the useEffect functionality based on any condition, we have to specify the list of dependencies. And the thumb rule is always to add those dependencies that you are using inside the useEffect(). 

4. When Component Unmounts

To clean up the mounting actions like removing event listeners or stopping data fetching with a side effect we call the useEffect after the component unmounts. A return statement with a function should be added inside the useEffect() hook. 

How the useEffect Hook Works (with Code)?

// use of useEffect in react for every rerender 
useEffect(() => { 
console.log("I run every time this component re-renders") 
}); 
//use of useEffect in react for onMount 
useEffect(() => { 
console.log("I Only run once (When the component gets mounted)") 
}, []); 
// Condition-based 
useEffect(() => { 
console.log("I run every time my condition is changed") 
}, [condition]); 
// Condition based with "clean up" 
useEffect(() => { 
console.log("I run every time my condition is changed") 
 
return () => { 
    console.log("Use this return as a 'clean up tool' (this runs before the actual code)") 
    } 
}, [condition]); 

React useEffect Examples

1. Effects Without Cleanup

Sometimes we want to execute additional code after React updates the DOM. Network requests, manual DOM mutations, and logging are common examples of effects that don’t require cleanup. Because we can do them and quickly forget them. Here's an example useEffect hook that relies on a variable, If the count variable updates, the effect will run again:

import { useState, useEffect } from "react"; 
import ReactDOM from "react-dom/client"; 
function Counter() { 
  const [count, setCount] = useState(0); 
  const [calculation, setCalculation] = useState(0); 
  useEffect(() => { 
    setCalculation(() => count * 2); 
  }, [count]); 
  return ( 
    <> 
      <p>Count: {count}</p> 
      <button onClick={() => setCount((c) => c + 1)}>+</button> 
      <p>Calculation: {calculation}</p> 
    </> 
  ); 
} 
const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Counter />); 

2. Effects with Cleanup

Earlier, we saw how to express side effects that don't require cleanup. However, some effects do. For example, in the below code, suppose we are using the below useEffect hook for an input field so that when a character is typed in the input field, an alert is shown after 1 second. But if the user doesn't wait for 1 second and types multiple letters in the input field, then cleanup is required to clean the previous alerts, which were to happen, and only the most recent alert will be called. 

useEffect(() => { 
 let isCancelled = false; 
 const changeHandler = async () => { 
 await timeout(1000); 
 if (!isCancelled) { 
 alert(`A name was changed: ${value}`); 
 } 
 }; 
 
 changeHandler(); 
 //The cleanup function is called when useEffect is called again or on unmount. 
 return () => { 
 isCancelled = true; 
 }; 
}, [value]); 

How to Fix Common Mistakes with useEffect?

Let's use a timer as an example. We will use setTimeout() to count 1 second after the initial render: 

import { useState, useEffect } from "react"; 
import ReactDOM from "react-dom/client"; 
function Timer() { 
  const [count, setCount] = useState(0); 
  useEffect(() => { 
    setTimeout(() => { 
      setCount((count) => count + 1); 
    }, 1000); 
  }); 
  return <h1>I've rendered {count} times!</h1>; 
} 
const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Timer />); 

Wait a second! ! It should only count once, but it keeps counting! react hooks useEffect runs on every render. In other words, when the counter changes, it renders and triggers another effect. we don't want that. There are several ways to control when side effects occur. You should always include a react useEffect second argument parameter that accepts an array. You can optionally pass dependencies to useEffect in this array. We can use an empty array to tackle this issue like this:-

useEffect(() => { 
  //only runs on the first render 
}, []); 

So to solve this problem, we only run this effect on the first render. Only run the effect on the first render.

import { useState, useEffect } from "react"; 
import ReactDOM from "react-dom/client"; 
function Timer() { 
  const [count, setCount] = useState(0); 
  useEffect(() => { 
    setTimeout(() => { 
      setCount((count) => count + 1); 
    }, 1000); 
  }, []); // empty array 
  return <h1>I've rendered {count} times!</h1>; 
} 
const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Timer />); 

Want more insights, check out the best React online course.  

Tips for Using React useEffect Hook

  • Control side effects effectively with useEffect.
  • Dependency Array: Define when to re-run the effect to avoid unnecessary updates.
  • Avoid Infinite Loops: Watch for state changes within the effect that might trigger loops.
  • Cleanup Function: Use it to clean up resources before unmount or next effect.
  • Conditional Execution: Control when the effect runs with conditional statements.
  • Separate Concerns: Break down complex effects into smaller, more manageable ones.
  • Functional Updates: Use functional updates when relying on previous state to avoid stale closures.
  • Debounce/Throttle: Consider techniques like debounce or throttle for frequent updates.

By adhering to these tips, you can harness the full potential of `useEffect` in React, ensuring efficient, well-controlled, and bug-free side effects within your functional components. 

Conclusion

Understanding the design concepts and best practices underlying useEffect hooks is an important skill to acquire if you want to become a next-level React developer. 

If you started your React journey before 2024, you need to throw away the instinct of thinking about lifecycle methods and instead start thinking about effects. Adopting a mental model of effects will get you familiar with component life cycles, data flow, and other hooks (useState, useRef, useContext, etc.).

Unlock new possibilities with our popular Software Engineering Courses. Check out the programs below to find your ideal match.

Explore the world of technology with our free Software Development Courses. Choose from the options below to find your perfect fit.

Frequently Asked Questions (FAQs)

1. What does useEffect do?

By using this Hook, you tell React that your component needs to do something after rendering. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates.

2. Why is useEffect called inside a component?

Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.

3. Does useEffect run after every render?

Yes! By default, it runs both after the first render and after every update.

4. How do I run useEffect on click?

You can use the useEffect hook on click by either triggering a state variable or by adding a listener inside the useEffect function.

5. How do you useEffect inside a function?

The useEffect runs by default after every render of the component. When placing useEffect in our component, we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates. 

If we pass only a callback, the callback will run after each render.

RELATED PROGRAMS