score:8

Accepted answer

there is no watcher on the actual dom. everytime the render function of a component gets called, the virtual dom gets re-build. if a component is no longer necessary, it gets removed from the virtual dom.

a diffing algorithm identifies those parts of the actual dom that need to be changed for the actual dom to be a reflection of the virtual dom: some components will have to be added to the actual dom (= called mounting), other components will have to be removed (= unmounting). this whole process is called reconciliation.

it is because of this reconciliation process, that react knows which components are to be removed from the actual dom. right before the component is removed, react calls the componentwillunmount() lifecycle hook.

if another script (javascript or jquery) causes the removal of a certain component from the actual dom, react will never notice it and therefore will not call the componentwillunmount() lifecycle hook.

score:5

this is not true. if you do manually remove a component from the dom it will not fire componentwillunmount.. it happens only via virtual dom, level if the component is not present anymore:

// 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 tested componentwillunmount by opening the devtools and removing some components that had componentwillunmount lifecycle method.


Related Query

More Query from same tag