8

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
}
Radex
  • 7,815
  • 23
  • 54
  • 86
  • Instead of directly accessing the DOM element you should use ref, Also react automatically will clear the reference since the class variable is destroyed, check this answer https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele/38093981#38093981 – Shubham Khatri Dec 19 '17 at 09:47
  • @ShubhamKhatri I understand you point in my real world app, this.elm is populated by a complex querySelectorAll, the dom is generated by another library so I cannot use ref. Should I use this.elm = null in my example – Radex Dec 19 '17 at 09:49
  • Yes, you need to manage the DOM references that you create yourself. – Bergi Dec 19 '17 at 09:55

1 Answers1

14

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

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43