Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use React useEffect hook to see how many times component mounts and unmounts


    In this lesson we are going to learn how to use useEffect hook from React 16.7 to be able to create a custom hook which allows us to see how often the component mounts and unmounts.

    Later, we can reuse it in other components and improve app performance by diving deep into how many times our components are mounted and/or unmounted.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: We have a simple app which allows us to toggle this test component over here, by clicking this button. The way that it works is that we change this type of this out component to be the opposite of the previous state, to either display or hide the component entirely.

    We would like to be able to get back how many times this test component has been mounted or unmounted. One way we could do it is basically be to console.log render, but we would like to use React hooks to achieve this effect in this component and also in other components in the future.

    We are going to import the useEffectHook from React. In order to debug how many times this component has been either mounted or unmounted, we're going to use the useEffectHook. It takes a function as an argument. This function is executed every time a component finishes its render phase, which also includes the first render, also known as mounting.

    useEffect also has a special behavior. If you return a function, this function's going to be executed whenever the component has been unmounted. After we save it, we can see our behavior in action. By default, after I refresh the page, the component is mounted, but if I toggle the component it's going to be unmounted and mounted. We can see the output in our debug.

    In order to use this debug tool in other components, we will need to create our own custom hook. To do that, create a new function. We're going to call it useDebug, and it is just a function that is going to execute our useEffectHook. I'm going to copy and paste it over here, and use this debug hook in our test component.

    It works exactly the same. For instance we could export this component to NPM, and have other developers use this in their applications.