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): Invoked after the **build()** function of the custom component is executed. 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: 70 71 (1) The backend component is directly removed from the component tree and destroyed. 72 73 (2) The reference to the destroyed component is released from the frontend components. 74 75 (3) The JS Engine garbage collects the destroyed component. 76 772. 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). 78 79 80Use 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. 81 82 83The following example shows when the lifecycle callbacks are invoked: 84 85```ts 86// Index.ets 87import { router } from '@kit.ArkUI'; 88 89@Entry 90@Component 91struct MyComponent { 92 @State showChild: boolean = true; 93 @State btnColor:string = "#FF007DFF"; 94 95 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 96 onPageShow() { 97 console.info('Index onPageShow'); 98 } 99 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 100 onPageHide() { 101 console.info('Index onPageHide'); 102 } 103 104 // Only components decorated by @Entry can call the lifecycle callbacks of a page. 105 onBackPress() { 106 console.info('Index onBackPress'); 107 this.btnColor ="#FFEE0606"; 108 return true // The value true means that the page executes its own return logic instead of the , and false (default) means that the default return logic is used. 109 } 110 111 // Component lifecycle 112 aboutToAppear() { 113 console.info('MyComponent aboutToAppear'); 114 } 115 116 // Component lifecycle 117 onDidBuild() { 118 console.info('MyComponent onDidBuild'); 119 } 120 121 // Component lifecycle 122 aboutToDisappear() { 123 console.info('MyComponent aboutToDisappear'); 124 } 125 126 build() { 127 Column() { 128 // When this.showChild is true, create the Child child component and invoke Child aboutToAppear. 129 if (this.showChild) { 130 Child() 131 } 132 // When this.showChild is false, delete the Child child component and invoke Child aboutToDisappear. 133 Button('delete Child') 134 .margin(20) 135 .backgroundColor(this.btnColor) 136 .onClick(() => { 137 this.showChild = false; 138 }) 139 // Push to the page and execute onPageHide. 140 Button('push to next page') 141 .onClick(() => { 142 router.pushUrl({ url: 'pages/page' }); 143 }) 144 } 145 } 146} 147 148@Component 149struct Child { 150 @State title: string = 'Hello World'; 151 // Component lifecycle 152 aboutToDisappear() { 153 console.info('[lifeCycle] Child aboutToDisappear'); 154 } 155 156 // Component lifecycle 157 onDidBuild() { 158 console.info('[lifeCycle] Child onDidBuild'); 159 } 160 161 // Component lifecycle 162 aboutToAppear() { 163 console.info('[lifeCycle] Child aboutToAppear'); 164 } 165 166 build() { 167 Text(this.title) 168 .fontSize(50) 169 .margin(20) 170 .onClick(() => { 171 this.title = 'Hello ArkUI'; 172 }) 173 } 174} 175``` 176```ts 177// page.ets 178@Entry 179@Component 180struct page { 181 @State textColor: Color = Color.Black; 182 @State num: number = 0; 183 184 onPageShow() { 185 this.num = 5; 186 } 187 188 onPageHide() { 189 console.log("page onPageHide"); 190 } 191 192 onBackPress() { // If the value is not set, false is used. 193 this.textColor = Color.Grey; 194 this.num = 0; 195 } 196 197 aboutToAppear() { 198 this.textColor = Color.Blue; 199 } 200 201 build() { 202 Column() { 203 Text (`num: ${this.num}`) 204 .fontSize(30) 205 .fontWeight(FontWeight.Bold) 206 .fontColor(this.textColor) 207 .margin(20) 208 .onClick(() => { 209 this.num += 5; 210 }) 211 } 212 .width('100%') 213 } 214} 215``` 216 217In 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. 218 219 220- The initialization process of application cold start is as follows: MyComponent aboutToAppear -> MyComponent build -> MyComponent onDidBuild -> Child aboutToAppear -> Child build -> Child onDidBuild -> Index onPageShow 221 222- 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. 223 224 225- 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. 226 227- If **router.replaceUrl** is called, the **Index** page is destroyed. In this case, the execution of lifecycle callbacks changes to: Index onPageHide -> MyComponent aboutToDisappear -> Child aboutToDisappear. As aforementioned, a component is destroyed by directly removing it from the component tree. Therefore, **aboutToDisappear** of the parent component is called first, followed by **aboutToDisappear** of the child component, and then the process of initializing the lifecycle of the new page is executed. 228 229- When the **Back** button is clicked, the **Index onBackPress** callback is invoked, and the current **Index** page is destroyed. 230 231- 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. 232 233 234- When the application exits, the following callbacks are executed in order: Index onPageHide -> MyComponent aboutToDisappear -> Child aboutToDisappear. 235 236## Custom Component's Listening for Page Changes 237 238You can use the listener API in [Observer](../reference/apis-arkui/js-apis-arkui-observer.md#observeronrouterpageupdate11) to listen for page changes in custom components. 239 240```ts 241// Index.ets 242import { uiObserver, router, UIObserver } from '@kit.ArkUI'; 243 244@Entry 245@Component 246struct Index { 247 listener: (info: uiObserver.RouterPageInfo) => void = (info: uiObserver.RouterPageInfo) => { 248 let routerInfo: uiObserver.RouterPageInfo | undefined = this.queryRouterPageInfo(); 249 if (info.pageId == routerInfo?.pageId) { 250 if (info.state == uiObserver.RouterPageState.ON_PAGE_SHOW) { 251 console.log(`Index onPageShow`); 252 } else if (info.state == uiObserver.RouterPageState.ON_PAGE_HIDE) { 253 console.log(`Index onPageHide`); 254 } 255 } 256 } 257 aboutToAppear(): void { 258 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 259 uiObserver.on('routerPageUpdate', this.listener); 260 } 261 aboutToDisappear(): void { 262 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 263 uiObserver.off('routerPageUpdate', this.listener); 264 } 265 build() { 266 Column() { 267 Text(`this page is ${this.queryRouterPageInfo()?.pageId}`) 268 .fontSize(25) 269 Button("push self") 270 .onClick(() => { 271 router.pushUrl({ 272 url: 'pages/Index' 273 }) 274 }) 275 Column() { 276 SubComponent() 277 } 278 } 279 } 280} 281@Component 282struct SubComponent { 283 listener: (info: uiObserver.RouterPageInfo) => void = (info: uiObserver.RouterPageInfo) => { 284 let routerInfo: uiObserver.RouterPageInfo | undefined = this.queryRouterPageInfo(); 285 if (info.pageId == routerInfo?.pageId) { 286 if (info.state == uiObserver.RouterPageState.ON_PAGE_SHOW) { 287 console.log(`SubComponent onPageShow`); 288 } else if (info.state == uiObserver.RouterPageState.ON_PAGE_HIDE) { 289 console.log(`SubComponent onPageHide`); 290 } 291 } 292 } 293 aboutToAppear(): void { 294 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 295 uiObserver.on('routerPageUpdate', this.listener); 296 } 297 aboutToDisappear(): void { 298 let uiObserver: UIObserver = this.getUIContext().getUIObserver(); 299 uiObserver.off('routerPageUpdate', this.listener); 300 } 301 build() { 302 Column() { 303 Text(`SubComponent`) 304 } 305 } 306} 307``` 308