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
}
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.
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.
componentWillUnmount. The componentWillUnmount method is called when the component is about to be removed 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With