Lightning Components Framework comes with a set of “system” events to notify components when the framework does something important. For example: “init” event is sent to every component when they are initially loaded. Similarly “rerender” event is sent when the framework thinks a component needs to be rerendered due to a button click or change in some attribute value.
But when there are multiple components, multiple events are triggered within each component and in various order. Understanding when these events are triggered and in what order can help us write better code and also identify potential performance issues due to things like “race condition”, “re-rendering” and more.
An Example App:
To understand it better, let’s build an app whose structure looks like the following:
A standalone app “Main App” that contains a single component “Parent Component”. Parent Component contains two Child components (Child1 and Child2). Further Child1 Component has two child components of it own(SubChild1 and SubChild2).
Below picture shows the actual app itself. It simply prints logs when a system event is triggered.
To Play With It:
1. Click here to install the “LiftCycleApp”.
2. Open the app in Chrome.
3. Open Chrome JS Debugger to see logs.
Test 1: Initial Load:
Let’s look at what happens when the app is first loaded. “init” (in JS controller), “render” (in renderer) and “afterRender” (in renderer) are called and in the following manner:
Test 2: Passing Data Via Attribute:
It is common to pass data from one component to another as an attribute. Let’s see how system events are triggered when that happens. In this case, when “Plus1” button in any of the 3 components is clicked, the value of “num” is incremented and is passed to the other components via attribute.
Scenario 1: Click on Plus1 button in “Main” App
Scenario 2: Click on Plus1 button in “Parent” component
Scenario 3: Click on Plus1 button in “SubChild1” component
- When there are multiple components, system events are triggered in “phases” . For example: “init” is called for each components and then in 2nd phase “render” is called for each component and so on.
The order in which events are sent across components differs a lot. Some start from top-level component first and some from innermost child component.
If you are listening to “change” event or “doneRendering” event and doing lot of work in those handlers, then you might hit performance issues.