Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a component is unmounted using react hooks?

I'm checking if a component is unmounted, in order to avoid calling state update functions.

  1. This is the first option, and it works
const ref = useRef(false)
  useEffect(() => {
    ref.current = true
    return () => {
      ref.current = false
    }
  }, [])

....
if (ref.current) {
  setAnswers(answers)
  setIsLoading(false)
}
....
  1. Second option is using useState, which isMounted is always false, though I changed it to true in component did mount
const [isMounted, setIsMounted] = useState(false)

useEffect(() => {
  setIsMounted(true)
  return () => {
    setIsMounted(false)
  }
}, [])

....
if (isMounted) {
  setAnswers(answers)
  setIsLoading(false)
}
....

Why is the second option not working compared with the first option?

like image 273
Henok Tesfaye Avatar asked Nov 21 '19 16:11

Henok Tesfaye


People also ask

How do you know if a component is unmounted React hooks?

The useEffect() hook is called when the component is mounted and sets the mounted. current value to true . The return function from the useEffect() hook is called when the component is unmounted and sets the mounted. current value to false .

How the component is unmounted in React?

The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.

How do you unmount a component in React hooks?

Use the useEffect hook to run a react hook when a component unmounts. The function we return from the useEffect hook gets invoked when the component unmounts and can be used for cleanup purposes. Copied!

How do you check if a component is rendered in React?

Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.


Video Answer


5 Answers

I wrote this custom hook that can check if the component is mounted or not at the current time, useful if you have a long running operation and the component may be unmounted before it finishes and updates the UI state.

import { useCallback, useEffect, useRef } from "react";

export function useIsMounted() {
  const isMountedRef = useRef(true);
  const isMounted = useCallback(() => isMountedRef.current, []);

  useEffect(() => {
    return () => void (isMountedRef.current = false);
  }, []);

  return isMounted;
}

Usage

function MyComponent() {
  const [data, setData] = React.useState()
  const isMounted = useIsMounted()

  React.useEffect(() => {
    fetch().then((data) => {
      // at this point the component may already have been removed from the tree
      // so we need to check first before updating the component state
      if (isMounted()) {
        setData(data)
      }
    })
  }, [...])

  return (...)
}

Live Demo

Edit 58979309/checking-if-a-component-is-unmounted-using-react-hooks

like image 199
NearHuscarl Avatar answered Oct 16 '22 19:10

NearHuscarl


This is a typescript version of @Nearhuscarl's answer.

import { useCallback, useEffect, useRef } from "react";
/**
 * This hook provides a function that returns whether the component is still mounted.
 * This is useful as a check before calling set state operations which will generates
 * a warning when it is called when the component is unmounted.
 * @returns a function
 */
export function useMounted(): () => boolean {
  const mountedRef = useRef(false);
  useEffect(function useMountedEffect() {
      mountedRef.current = true;
      return function useMountedEffectCleanup() {
        mountedRef.current = false;
      };
    }, []);
  return useCallback(function isMounted() {
      return mountedRef.current;
    }, [mountedRef]);
}

This is the jest test

import { render, waitFor } from '@testing-library/react';
import React, { useEffect } from 'react';
import { delay } from '../delay';
import { useMounted } from "./useMounted";

describe("useMounted", () => {

  it("should work and not rerender", async () => {
    const callback = jest.fn();

    function MyComponent() {
      const isMounted = useMounted();

      useEffect(() => {
        callback(isMounted())
      }, [])

      return (<div data-testid="test">Hello world</div>);
    }

    const { unmount } = render(<MyComponent />)
    expect(callback.mock.calls).toEqual([[true]])
    unmount();
    expect(callback.mock.calls).toEqual([[true]])

  })

  it("should work and not rerender and unmount later", async () => {
    jest.useFakeTimers('modern');
    const callback = jest.fn();

    function MyComponent() {
      const isMounted = useMounted();

      useEffect(() => {
        (async () => {
          await delay(10000);
          callback(isMounted());
        })();
      }, [])

      return (<div data-testid="test">Hello world</div>);
    }

    const { unmount } = render(<MyComponent />)
    await waitFor(() => expect(callback).toBeCalledTimes(0));
    jest.advanceTimersByTime(5000);
    unmount();
    jest.advanceTimersByTime(5000);
    await waitFor(() => expect(callback).toBeCalledTimes(1));
    expect(callback.mock.calls).toEqual([[false]])
  })

})

Sources available in https://github.com/trajano/react-hooks-tests/tree/master/src/useMounted

like image 41
Archimedes Trajano Avatar answered Oct 16 '22 19:10

Archimedes Trajano


This cleared up my error message, setting a return in my useEffect cancels out the subscriptions and async tasks.

  import React from 'react'

  const MyComponent = () => {
    
   const [fooState, setFooState] = React.useState(null)

   React.useEffect(()=> {

    //Mounted
     getFetch()
        

    // Unmounted
     return () => {
        setFooState(false)
     }
   })

      return (
        <div>Stuff</div>
      )
    }

export {MyComponent as default}
like image 23
jamjad Avatar answered Oct 16 '22 18:10

jamjad


Please read this answer very carefully until the end.

It seems your component is rendering more than one time and thus the isMounted state will always become false because it doesn't run on every update. It just run once and on unmounted. So, you'll do pass the state in the second option array:

}, [isMounted])

Now, it watches the state and run the effect on every update. But why the first option works?

It's because you're using useRef and it's a synchronous unlike asynchronous useState. Read the docs about useRef again if you're unclear:

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.


BTW, you do not need to clean up anything. Cleaning up the process is required for DOM changes, third-party api reflections, etc. But you don't need to habit on cleaning up the states. So, you can just use:

useEffect(() => {
    setIsMounted(true)
}, []) // you may watch isMounted state
     // if you're changing it's value from somewhere else

While you use the useRef hook, you are good to go with cleaning up process because it's related to dom changes.

like image 9
Bhojendra Rauniyar Avatar answered Oct 16 '22 18:10

Bhojendra Rauniyar


If you want to use a small library for this, then react-tidy has a custom hook just for doing that called useIsMounted:

import React from 'react'
import {useIsMounted} from 'react-tidy'

function MyComponent() {
  const [data, setData] = React.useState(null)
  const isMounted = useIsMounted()
  React.useEffect(() => {
    fetchData().then((result) => {
      if (isMounted) {
        setData(result)
      }
    })
  }, [])
  // ...
}

Learn more about this hook

Disclaimer I am the writer of this library.

like image 1
webNeat Avatar answered Oct 16 '22 20:10

webNeat