HomeBlogWeb DevelopmentReact useEffect() Hook: Structure, Usage, Examples & Tips

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

Published
01st Jul, 2024
Views
view count loader
Read it in
10 Mins
In this article
    React useEffect() Hook: Structure, Usage, Examples & Tips

    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 the best 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 this from the 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? 
    useEffect
    Telerik.com

    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> KnowledgeHut By 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 KnowledgeHut. 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? 
    Side Effect in 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. 

    Unlock the power of coding with Python! Discover the endless possibilities of this versatile language. Join our online Python programming course and learn at your own pace. Start your coding journey today!

    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.). Want to learn more web development skills? Check out the best course for Web Development. 

    Frequently Asked Questions (FAQs)

    1What 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.

    2Why 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.

    3Does useEffect run after every render?

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

    4How 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. 

    5How 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.

    Profile

    Mritunjay Gupta

    Author

    I'm an undergraduate student who is passionate about solving real-life problems. I'm fascinated by software development and product management. I love to learn new stuff that interests me and can help me get better at what I do. I love to work with people who are passionate about building solutions.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon