pitrackster pitrackster - 9 months ago 64
Javascript Question

ReactJs how to know when a component is removed from DOM

I'm currently facing a problem with React. I need to know when a component is removed from DOM.

All I find in component lifecycle is componentWillUnmount which gets called before the component is removed from DOM.

Is there any way to achieve this with React ?
In plain javascript ?



"Plain javascript" === Not using a library ;-)

My use case is the use of jsPlumb within a react component.

Basically jsPlumb is a library that draws svg in the DOM with position calculation.

In my main component there is a list of items.
Each item is a component.
On each rendered item I use JsPlumb to draw on it.

But... When I remove an item of the list the items are changing there positions in the DOM so I need to ask to jsPlumb to redraw things based on new positions. So that's why I need to know when component is fully removed from DOM.

Answer Source

Ok thanks to all ! I found a solution that fits my needs and is (IMHO) clean...

In my parent component I handle componentDidUpdate lifecycle event and in there I can know (with prevProps and props) if the changes that are made need to fire my action...

class MyComponent extends Component {
    // this one is called each time any props is changed
    componentDidUpdate(prevProps, prevState) {
       // if condition is matched then do something