1# Page and Custom Component Lifecycle 2 3 4Before we dive into the page and custom component lifecycle, it would be helpful to learn the relationship between custom components and pages. 5 6 7- Custom component: \@Component decorated UI unit, which can combine multiple built-in components for component reusability and invoke component lifecycle callbacks. 8 9- Page: UI page of an application. A page can consist of one or more custom components. A custom component decorated with @Entry is used as the default entry component of the page. Exactly one component can be decorated with \@Entry in a single source file. Only components decorated by \@Entry can call the lifecycle callbacks of a page. 10 11 12The following lifecycle callbacks are provided for a page, that is, a custom component decorated with \@Entry: 13 14 15- [onPageShow](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#onpageshow): Invoked each time the page is displayed, for example, during page redirection or when the application is switched to the foreground. 16 17- [onPageHide](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#onpagehide): Invoked each time the page is hidden, for example, during page redirection or when the application is switched to the background. 18 19- [onBackPress](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#onbackpress): Invoked when the user clicks the **Back** button. 20 21 22The following lifecycle callbacks are provided for a custom component decorated with \@Component: 23 24 25- [aboutToAppear](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear): Invoked when the custom component is about to appear. Specifically, it is invoked after a new instance of the custom component is created and before its **build** function is executed. 26 27- [onDidBuild](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#ondidbuild12): This API is called back after **build()** of the component is executed. In this phase, you can report tracking data without affecting the actual UI functions. Do not change state variables or use functions (such as **animateTo**) in **onDidBuild**. Otherwise, unstable UI performance may result. 28 29- [aboutToDisappear](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#abouttodisappear): Invoked when the custom component is about to be destroyed. Do not change state variables in the **aboutToDisappear** function as doing this can cause unexpected errors. For example, the modification of the **@Link** decorated variable may cause unstable application running. 30 31 32The following figure shows the lifecycle of a component (page) decorated with \@Entry. 33 34 35 36 37 38Based on the preceding figure, let's look into the creation, re-rendering, and deletion of a custom component. 39 40 41## Custom Component Creation and Rendering 42 431. Custom component creation: An instance of a custom component is created by the ArkUI framework. 44 452. Initialization of custom component member variables: The member variables are initialized with locally defined defaults or component constructor parameters. The initialization happens in the document order, which is the order in which the member variables are defined. 46 473. If defined, the component's **aboutToAppear** callback is invoked. 48 494. On initial render, the **build** function of the built-in component is executed for rendering. If the child component is a custom component, the rendering creates an instance of the child component. During initial render, the framework records the mapping between state variables and components. When a state variable changes, the framework drives the related components to update. 50 515. If defined, the component's **onDidBuild** callback is invoked. 52 53 54## Custom Component Re-rendering 55 56Re-rending of a custom component is triggered when its state variable is changed by an event handle (for example, when the click event is triggered) or by an update to the associated attribute in LocalStorage or AppStorage. 57 58 591. The framework observes the state variable change and marks the component for re-rendering. 60 612. Using the mapping tables – created in step 4 of the [custom component creation and rendering process](#custom-component-creation-and-rendering), the framework knows which UI components are managed by the state variable and which update functions are used for these UI components. With this knowledge, the framework executes only the update functions of these UI components. 62 63 64## Custom Component Deletion 65 66A custom component is deleted when the branch of the **if** statement or the number of arrays in **ForEach** changes. 67 68 691. Before the component is deleted, the **aboutToDisappear** callback is invoked to mark the component for deletion. The component deletion mechanism of ArkUI is as follows:<br>(1) The backend component is directly removed from the component tree and destroyed.<br>(2) The reference to the destroyed component is released from the frontend components.<br>(3) The JS Engine garbage collects the destroyed component. 70 712. The custom component and all its variables are deleted. Any variables linked to this component, such as [@Link](arkts-link.md), [@Prop](arkts-prop.md), or [@StorageLink](arkts-appstorage.md#storagelink) decorated variables, are unregistered from their [synchronization sources](arkts-state-management-overview.md#basic-concepts). 72 73 74Use of **async await** is not recommended inside the **aboutToDisappear** callback. In case of an asynchronous operation (a promise or a callback) being started from the **aboutToDisappear** callback, the custom component will remain in the Promise closure until the function is executed, which prevents the component from being garbage collected. 75 76 77The following example shows when the lifecycle callbacks are invoked: 78 79```ts 80// Index.ets 81import { router } from '@kit.ArkUI'; 82 83@Entry 84@Component 85struct MyComponent { 86 @State showChild: boolean = true; 87 @State btnColor: string = "#FF007DFF"; 88 89 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 90 onPageShow() { 91 console.info('Index onPageShow'); 92 } 93 94 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 95 onPageHide() { 96 console.info('Index onPageHide'); 97 } 98 99 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 100 onBackPress() { 101 console.info('Index onBackPress'); 102 this.btnColor = "#FFEE0606"; 103 return true // The value true means that the page executes its own return logic, and false means that the default return logic is used. 104 } 105 106 // Component lifecycle 107 aboutToAppear() { 108 console.info('MyComponent aboutToAppear'); 109 } 110 111 // Component lifecycle 112 onDidBuild() { 113 console.info('MyComponent onDidBuild'); 114 } 115 116 // Component lifecycle 117 aboutToDisappear() { 118 console.info('MyComponent aboutToDisappear'); 119 } 120 121 build() { 122 Column() { 123 // When this.showChild is true, create the Child child component and invoke Child aboutToAppear. 124 if (this.showChild) { 125 Child() 126 } 127 Button('delete Child') 128 .margin(20) 129 .backgroundColor(this.btnColor) 130 .onClick(() => { 131 // When this.showChild is false, delete the Child child component and invoke Child aboutToDisappear. 132 this.showChild = false; 133 }) 134 // Push to Page and execute onPageHide. 135 Button('push to next page') 136 .onClick(() => { 137 router.pushUrl({ url: 'pages/Page' }); 138 }) 139 } 140 } 141} 142 143@Component 144struct Child { 145 @State title: string = 'Hello World'; 146 // Component lifecycle 147 aboutToDisappear() { 148 console.info('[lifeCycle] Child aboutToDisappear'); 149 } 150 151 // Component lifecycle 152 onDidBuild() { 153 console.info('[lifeCycle] Child onDidBuild'); 154 } 155 156 // Component lifecycle 157 aboutToAppear() { 158 console.info('[lifeCycle] Child aboutToAppear'); 159 } 160 161 build() { 162 Text(this.title) 163 .fontSize(50) 164 .margin(20) 165 .onClick(() => { 166 this.title = 'Hello ArkUI'; 167 }) 168 } 169} 170``` 171```ts 172// Page.ets 173@Entry 174@Component 175struct Page { 176 @State textColor: Color = Color.Black; 177 @State num: number = 0; 178 179 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 180 onPageShow() { 181 this.num = 5; 182 } 183 184 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 185 onPageHide() { 186 console.log("Page onPageHide"); 187 } 188 189 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 190 onBackPress() { // If the value is not set, false is used. 191 this.textColor = Color.Grey; 192 this.num = 0; 193 } 194 195 // Component lifecycle 196 aboutToAppear() { 197 this.textColor = Color.Blue; 198 } 199 200 build() { 201 Column() { 202 Text (`num: ${this.num}`) 203 .fontSize(30) 204 .fontWeight(FontWeight.Bold) 205 .fontColor(this.textColor) 206 .margin(20) 207 .onClick(() => { 208 this.num += 5; 209 }) 210 } 211 .width('100%') 212 } 213} 214``` 215 216In the preceding example, the **Index** page contains two custom components. One is **MyComponent** decorated with \@Entry, which is also the entry component (root node) of the page. The other is **Child**, which is a child component of **MyComponent**. Only components decorated by \@Entry can call the page lifecycle callbacks. Therefore, the lifecycle callbacks of the **Index** page – **onPageShow**, **onPageHide**, and **onBackPress**, are declared in **MyComponent**. In **MyComponent** and its child components, component lifecycle callbacks – **aboutToAppear**, **onDidBuild**, and **aboutToDisappear** – are also declared. 217 218 219- The initialization process of application cold start is as follows: **MyComponent aboutToAppear** -> **MyComponent build** -> **MyComponent onDidBuild** -> **Child aboutToAppear** -> **Child build** -> **Child onDidBuild** -> **Index onPageShow** 220 221- When **delete Child** is clicked, the value of **this.showChild** linked to **if** changes to **false**. As a result, the **Child** component is deleted, and the **Child aboutToDisappear** callback is invoked. 222 223 224- When **push to next page** is clicked, the **router.pushUrl** API is called to jump to the next page. As a result, the **Index** page is hidden, and the **Index onPageHide** callback is invoked. As the called API is **router.pushUrl**, which results in the Index page being hidden, but not destroyed, only the **onPageHide** callback is invoked. After a new page is displayed, the process of initializing the lifecycle of the new page is executed. 225 226- If **router.replaceUrl** is called, the current index page is destroyed. As mentioned above, the component destruction is to detach the subtree from the component tree. Therefore, the executed lifecycle process is changed to the initialization lifecycle process of the new page and then execute **Index onPageHide** -> **MyComponent aboutToDisappear** -> **Child aboutToDisappear**. 227 228- When the **Back** button is clicked, the **Index onBackPress** callback is invoked, and the current **Index** page is destroyed. 229 230- When the application is minimized or switched to the background, the **Index onPageHide** callback is invoked. As the current **Index** page is not destroyed, **aboutToDisappear** of the component is not executed. When the application returns to the foreground, the **Index onPageShow** callback is invoked. 231 232 233- When the application exits, the following callbacks are executed in order: **Index onPageHide** -> **MyComponent aboutToDisappear** -> **Child aboutToDisappear**. 234 235## Custom Component's Listening for Page Changes 236 237You can use the listener API in [Observer](../reference/apis-arkui/js-apis-arkui-observer.md#observeronrouterpageupdate11) to listen for page changes in custom components. 238 239```ts 240// Index.ets 241import { uiObserver, router, UIObserver } from '@kit.ArkUI'; 242 243@Entry 244@Component 245struct Index { 246 listener: (info: uiObserver.RouterPageInfo) => void = (info: uiObserver.RouterPageInfo) => { 247 let routerInfo: uiObserver.RouterPageInfo | undefined = this.queryRouterPageInfo(); 248 if (info.pageId == routerInfo?.pageId) { 249 if (info.state == uiObserver.RouterPageState.ON_PAGE_SHOW) { 250 console.log(`Index onPageShow`); 251 } else if (info.state == uiObserver.RouterPageState.ON_PAGE_HIDE) { 252 console.log(`Index onPageHide`); 253 } 254 } 255 } 256 aboutToAppear(): void { 257 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 258 uiObserver.on('routerPageUpdate', this.listener); 259 } 260 aboutToDisappear(): void { 261 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 262 uiObserver.off('routerPageUpdate', this.listener); 263 } 264 build() { 265 Column() { 266 Text(`this page is ${this.queryRouterPageInfo()?.pageId}`) 267 .fontSize(25) 268 Button("push self") 269 .onClick(() => { 270 router.pushUrl({ 271 url: 'pages/Index' 272 }) 273 }) 274 Column() { 275 SubComponent() 276 } 277 } 278 } 279} 280@Component 281struct SubComponent { 282 listener: (info: uiObserver.RouterPageInfo) => void = (info: uiObserver.RouterPageInfo) => { 283 let routerInfo: uiObserver.RouterPageInfo | undefined = this.queryRouterPageInfo(); 284 if (info.pageId == routerInfo?.pageId) { 285 if (info.state == uiObserver.RouterPageState.ON_PAGE_SHOW) { 286 console.log(`SubComponent onPageShow`); 287 } else if (info.state == uiObserver.RouterPageState.ON_PAGE_HIDE) { 288 console.log(`SubComponent onPageHide`); 289 } 290 } 291 } 292 aboutToAppear(): void { 293 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 294 uiObserver.on('routerPageUpdate', this.listener); 295 } 296 aboutToDisappear(): void { 297 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 298 uiObserver.off('routerPageUpdate', this.listener); 299 } 300 build() { 301 Column() { 302 Text(`SubComponent`) 303 } 304 } 305} 306``` 307