Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I remove a reference to a DOM element when a component unmount in react?

I have a react component which take a dom reference when mounting (I know this is an edge case). I would like to know if it is necessary set to null the property which host the dom. Or does react take care of it?

componentDidMount() {
   this.elm = document.getElementById('foo')
}

componentWillUnmount(){
   this.elm = null
}
like image 461
Radex Avatar asked Dec 19 '17 09:12

Radex


People also ask

How do I unmount a component from a DOM?

All you have to do is remove it from the DOM in order to unmount it. As long as renderMyComponent = true , the component will render. If you set renderMyComponent = false , it will unmount from the DOM.

What happens in component unmount?

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.

Which of the below methods helps in unmounting a component from the dom?

componentWillUnmount. The componentWillUnmount method is called when the component is about to be removed from the DOM.

Which method is fired when the component is unmounted from the dom?

componentWillUnmount() This method is called before the unmounting of the component takes place. Before the removal of the component from the DOM, 'componentWillUnMount' executes. This method denotes the end of the component's lifecycle. That's all about this important part of the React world — lifecycle methods.


1 Answers

By react documentation you need only to clean up globals elements such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

A reference will be destroyed with the component on unmount cycle.

https://reactjs.org/docs/react-component.html#componentwillunmount

like image 78
Mosè Raguzzini Avatar answered Sep 27 '22 21:09

Mosè Raguzzini