For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentReact useEffect() Hook: Basic Usage, When and How to Use It?

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

Published
14th Feb, 2024
Views
view count loader
Read it in
10 Mins
In this article
    React useEffect() Hook: Basic Usage, When and How to Use It?

    Hello Readers! Welcome to the world of modern JavaScript! Or should I say, the world of React! 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 React useEffect Hook? 

    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.  

    Does all this sound new and fascinating to you? 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)") 
    }, []); 


    Structure of useEffect Hook

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

    The key Concepts of Using Effects

    Before we move further, below are the key concepts of the useEffect hook:- 

    • Before using useEffect hook, you need to know exactly when the component will be (re)rendered, as effects are executed after each rendering cycle. 
    • Effects are always run after rendering, but there is an option to opt out of this behavior. 
    • Rejecting or skipping an effect requires understanding basic JavaScript concepts about values. The effect will only run again if at least one of the values specified in the effect's dependencies has changed since the last rendering cycle. 
    • Components should not be re-rendered unnecessarily. This is another strategy for skipping unnecessary repetitions of effects. 
    • It should be understood that functions defined in the body of a function component are rebuilt every render cycle. This has implications when used within effects. There is a strategy to deal with this (pull it up outside the component, define it inside the effect, use useCallback). 
    • You should understand basic JavaScript concepts such as old closures. If you don't understand this, you can struggle to resolve issues with stale props and state values in your effects. I have a strategy to solve this. B. Using the Effect Dependency Array or useRef hooks. 
    • Don't ignore suggestions from the React Hooks ESLint plugin. Don't blindly remove dependencies (ignoring ESLint warnings blindly) or carelessly use ESLint's disabled comments. An error has likely occurred. 

    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? 

    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 

    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 />); 

    Effects with Cleanup

    Earlier we've seen 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 />); 

    Using Async and Await in React useEffect   

    The following piece of code demonstrates the use of using async await with react hooks useEffect. In the below example we are requesting to get the users with the help of async await. Want more insights, check out the best React online course 

    const [users, setUsers] = useState([]); 
    useffect(() => { 
      const getUsers = async () => { 
        let response = await fetch('/users'); 
        let data = await response.json(); 
        setUsers(data); 
      }; 
     getUsers(); 
    }, []); 

    Tips for Using Effects

    Effectively employing the hook useEffect in React demands a nuanced approach. While its flexibility empowers developers to manage side effects seamlessly, a few tips can enhance its usage, ensuring optimal performance and maintainability. 

    1. Dependency Array: Be intentional when crafting the dependency array. It dictates when the effect should re-run. If omitted, the effect runs after every render. However, if specified, it should include all values from the component scope that are used within the effect. Be cautious with dependencies that may change frequently, as it could lead to excessive re-renders.

    2. Avoiding Infinite Loops: Ensure that the effect doesn't inadvertently trigger an infinite loop. If the effect changes a state value that's used within the same effect, it can cause continuous re-execution. Use dependencies or cleanup functions strategically to break such loops.

    3. Cleanup Logic: Leverage the cleanup function to manage resource cleanup, subscriptions, or any side effect that requires explicit teardown. This function runs before the component unmounts or before the next effect, contributing to a clean and efficient component lifecycle.

    4. Conditional Execution: Introduce conditional statements within the effect to control when it should run. This can be especially useful when dealing with specific conditions or when you want the effect to run only under certain circumstances.

    5. Separate Concerns: When dealing with multiple side effects, consider splitting them into separate `useEffect` hooks. This not only improves code readability but also provides better control over each specific side effect.

    6. Functional Updates: When the effect relies on the previous state, use the functional update pattern. This ensures that you're working with the latest state and helps avoid potential issues with stale closures.

    useEffect(() => {
     setCount((prevCount) => prevCount + 1);
    }, [dependency]);

    7. Debouncing and Throttling: Apply debouncing or throttling techniques for frequent updates to prevent overwhelming requests or computations. Libraries like Lodash provide helpful functions like `debounce` and `throttle` for such scenarios.

    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.

    Call hooks first at the top level. 

    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 2019, 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