Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a component unmount?

My current understanding is that a component mounts onto the DOM when it is needed to be seen or when the route requires that component. It will also render its child components. Does this mean that a component will be unmounted when you visit a route that doesn't have that component or whenever you visit any page that doesn't show the element that component produces? Thus, a component will need to be remounted every time it shows up on the DOM (outside of prop and state changes), correct?

like image 548
stackjlei Avatar asked Jan 06 '17 04:01

stackjlei


People also ask

Why does a component unmount?

Components are unmounted when the parent component is no longer rendered or the parent component performs an update that does not render this instance. ReactDOM. unmountComponentAtNode will also trigger an unmount.

What does component unmounting mean?

componentWillUnmount is the last function to be called immediately before the component is removed from the DOM. It is generally used to perform clean-up for any DOM-elements or timers created in componentWillMount . At a picnic, componentWillUnmount corresponds to just before you pick up your picnic blanket.

When component will unmount is called?

ReactJS – componentWillUnmount() Method This method is called during the unmounting phase of the React Lifecycle, i.e., before the component is destroyed or unmounted from the DOM tree. This method is majorly used to cancel all the subscriptions that were previously created in the componentWillMount method.

Can a component unmount itself?

You can just unmount it conditionally. 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.


1 Answers

During the VirtualDOM Reconciliation if a component existed but no longer will, the component is considered unmounted and given a chance to clean up (via componentWillUnmount).

The reverse is true, during the reconciliation, if a component didn't exist, but now does, the component is considered ready to mount, and given a chance to prep itself (constructor / componentWillMount)

When tearing down a tree, old DOM nodes are destroyed. Component instances receive componentWillUnmount(). When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.

https://facebook.github.io/react/docs/reconciliation.html

That particular page is well worth a read if you haven't already. It also explains why key is pretty important for repeated elements.

like image 106
Chris Avatar answered Oct 16 '22 08:10

Chris