Vue Parent and Child lifecycle hooks
If you have built anything in Vue, I am sure you will be familiar with the component lifecycle hooks, but you may not be aware of the unintuitive order that these hooks will fire when dealing with parent and child components and what affect that may have on your props.
Parent/Child lifecycle hooks
The example below outputs a message when the Mounted and Created hooks are fired in a parent and child setup. As you can see, the Created hooks are fired in the order that you may expect, but the Mounted hooks are fired in the opposite order.
This may be hard to grasp at first, but if we follow the component initialisation workflow through logically we can understand this ordering. We just need to remember that the parent component will wait for its children to mount before it mounts its own template to the DOM.
The ordering of these hooks becomes very important if your components are communicating through props.
Reactivity in Props
A component becomes reactive just before the Created hook is fired, this means it will start to track changes of it’s props before it’s parent’s Mounted hook has fired. This is worth remembering if you have logic setting the value of a prop in the parent’s Mounted hooks.
The example below shows the difference between preparing your prop data in both the Created and Mounted hooks of the parent component. As you can see, the prop that was set in the Mounted hook reacts twice on the child component.
Imagine if your child component made an Ajax request every time this prop changes, this would cause twice as much network activity and this could easily respond out of order.
If you want a deeper dive into Vue lifecycle hooks, I highly recommend the following article…
Lifecycle hooks are an important part of any serious component. You often need to know when your component is created…alligator.io
But as a quick rule of thumb, I suggest only using the Mounted hook if your component needs to interact with the DOM, anything else should probably be taken care of in the Created hook.