Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if the react component is unmounted?

I have a usecase where i need to unmount my react component. But in some cases, the particular react component is unmounted by a different function. Hence, I need to check if the component is mounted before unmounting it.

like image 469
Dharini S Avatar asked Sep 29 '16 10:09

Dharini S


People also ask

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.

Is component mounted React?

Almost everything follows this cycle in its life, and React components do as well. Components are created (mounted on the DOM), grow by updating, and then die (unmount on DOM).

What is unmounted in React?

The main job of React is to figure out how to modify the DOM to match what the components want to be rendered on the screen. React does so by "mounting" (adding nodes to the DOM), "unmounting" (removing them from the DOM), and "updating" (making changes to nodes already in the DOM).

When component will unmount is called in React?

componentWillUnmount is the last function to be called immediately before the component is removed from the DOM. It is generally used to perform clean-up for any DOM-elements or timers created in componentWillMount . At a picnic, componentWillUnmount corresponds to just before you pick up your picnic blanket.


2 Answers

Since isMounted() is being officially deprecated, you can do this in your component:

componentDidMount() {    this._ismounted = true; }  componentWillUnmount() {    this._ismounted = false; } 

This pattern of maintaining your own state variable is detailed in the ReactJS documentation: isMounted is an Antipattern.

like image 125
Shubham Khatri Avatar answered Sep 18 '22 09:09

Shubham Khatri


I'll be recommended you to use the useRef hook for keeping track of component is mounted or not because whenever you update the state then react will re-render the whole component and also it will trigger the execution of useEffect or other hooks.

function MyComponent(props: Props) {   const isMounted = useRef(false)    useEffect(() => {     isMounted.current = true;     return () => { isMounted.current = false }   }, []);    return (...); }  export default MyComponent; 

and you check if the component is mounted with if (isMounted.current) ...

like image 25
Sagar Avatar answered Sep 19 '22 09:09

Sagar