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?

Show source
| javascript   | reactjs   2017-01-06 05:01 3 Answers

Answers to When does a component unmount? ( 3 )

  1. 2017-01-06 05:01

    I would say a component mount onto the DOM only if it's used via another component, including a Router component. Don't think of routers as special elements/things in React. They're like other components and they do a matching between current URL and the patterns they have to decide which component should be rendered via the render() function of Router. Whenever there is a change of URL, the router picks the new component to render and does rendering via render() function.

  2. 2017-01-06 05:01

    If the component need render, it should be mounted onto DOM.

    If not, but be mounted before, if should be unmounted.

  3. 2017-01-06 06:01

    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.


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

Leave a reply to - When does a component unmount?

◀ Go back