How does React know that a component has been removed from the DOM?

In Adding Lifecycle Methods to Classes , official Facebook docs for React mentioned:

5) If the Clock component has ever been removed from the DOM, React calls hookObjectUnmount () to stop the timer.

Just trying to figure out how? I get that React knows when it is about to insert a component in the DOM, so it can call componentDidMount hook for the life cycle.

But for componentWillUnmount it simply says " ever removed from the DOM ". This seems to be a real DOM, not a React DOM. You can also remove the component with javaScript / jQuery and componentWillUnmount should fire.

How exactly does React know that the component has been removed from the real DOM? Could there be an observer?

thanks

+5
source share
2 answers

There is no observer in the real DOM. Each time a component rendering function is called, the virtual DOM is restored. If the component is no longer needed, it is removed from the virtual DOM.

The difference algorithm identifies the parts of the actual DOM that need to be changed so that the actual DOM is a reflection of the virtual DOM: some components must be added to the actual DOM (= called mounting), other components will need to be removed (= unmount). This whole process is called reconciliation .

It is because of this reconciliation process that React knows which components should be removed from the actual DOM. Right before the component is removed, React calls the hookObject () of the componentWillUnmount () life cycle.

If another script (Javascript or jQuery) removes a specific component from the actual DOM, React will never notice it and therefore will not call hookCycleUillmount ().

+3
source

This is not true. IF you manually remove the component from the DOM, it does not start componentWillUnmount . This only happens through the Virtual DOM level if the component is no longer present:

 // Unmount children that are no longer present. for (name in prevChildren) { if ( prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name)) ) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent( prevChild, false /* safely */, false /* skipLifecycle */, ); } } 

https://github.com/facebook/react/blob/5c6a496d98b80d19d851c2ec3a56d760b7118a50/src/renderers/shared/stack/reconciler/ReactChildReconciler.js

unmountComponent will then call componentWillUnmount .

I manually checked componentWillUnmount by opening devtools and removing some components that had the componentWillUnmount lifecycle method.

+2
source

Source: https://habr.com/ru/post/1269652/


All Articles