• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Custom Component Lifecycle
2
3The lifecycle callbacks of a custom component are used to notify users of the lifecycle of the component. These callbacks are private and are invoked by the development framework at a specified time at runtime. They cannot be manually invoked from applications. Do not reuse the same custom component node across multiple windows, as otherwise its lifecycle may become disrupted.
4
5>**NOTE**
6>
7>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>- Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters.
9
10
11## aboutToAppear
12
13aboutToAppear?(): void
14
15Invoked after a new instance of the custom component is created and before its **build()** function is executed. You can change state variables in **aboutToAppear**. The change will take effect when you execute the **build()** function next time. The **aboutToAppear** lifecycle callback of a custom component with a custom layout is invoked during the layout process.
16
17**Widget capability**: This API can be used in ArkTS widgets since API version 9.
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23## onDidBuild<sup>12+</sup>
24
25onDidBuild?(): void
26
27Invoked after the **build()** function of the custom component is executed. You can use this callback for actions that do not directly affect the UI, such as tracking data reporting. Do not change state variables or use functions (such as **animateTo**) in **onDidBuild**. Otherwise, unstable UI performance may result.
28
29**Atomic service API**: This API can be used in atomic services since API version 12.
30
31**System capability**: SystemCapability.ArkUI.ArkUI.Full
32
33## aboutToDisappear
34
35aboutToDisappear?(): void
36
37Invoked when this component is about to disappear. 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.
38
39**Widget capability**: This API can be used in ArkTS widgets since API version 9.
40
41**Atomic service API**: This API can be used in atomic services since API version 11.
42
43**System capability**: SystemCapability.ArkUI.ArkUI.Full
44
45## onPageShow
46
47onPageShow?(): void
48
49Invoked each time the page is displayed, for example, during page redirection or when the application is switched to the foreground. It works only for the custom components decorated by **@Entry**.
50
51**Atomic service API**: This API can be used in atomic services since API version 11.
52
53**System capability**: SystemCapability.ArkUI.ArkUI.Full
54
55## onPageHide
56
57onPageHide?(): void
58
59Invoked each time the page is hidden, for example, during page redirection or when the application is switched to the background. It works only for the custom components decorated by **@Entry**.
60
61**Atomic service API**: This API can be used in atomic services since API version 11.
62
63**System capability**: SystemCapability.ArkUI.ArkUI.Full
64
65## onBackPress
66
67onBackPress?(): void | boolean
68
69Invoked when the user clicks the Back button. It works only for the custom components decorated by @Entry. The value **true** means that the page executes its own return logic, and **false** (default) means that the default return logic is used.
70
71**Atomic service API**: This API can be used in atomic services since API version 11.
72
73**System capability**: SystemCapability.ArkUI.ArkUI.Full
74
75```ts
76// xxx.ets
77@Entry
78@Component
79struct IndexComponent {
80  @State textColor: Color = Color.Black;
81
82  onPageShow() {
83    this.textColor = Color.Blue;
84    console.info('IndexComponent onPageShow');
85  }
86
87  onPageHide() {
88    this.textColor = Color.Transparent;
89    console.info('IndexComponent onPageHide');
90  }
91
92  onBackPress() {
93    this.textColor = Color.Red;
94    console.info('IndexComponent onBackPress');
95  }
96
97  build() {
98    Column() {
99      Text('Hello World')
100        .fontColor(this.textColor)
101        .fontSize(30)
102        .margin(30)
103    }.width('100%')
104  }
105}
106```
107![en-us_image_lifecycle](figures/en-us_image_lifecycle.gif)
108
109## aboutToReuse<sup>10+</sup>
110
111aboutToReuse?(params: { [key: string]: unknown }): void
112
113Invoked when a reusable custom component is re-added to the node tree from the reuse cache to receive construction parameters of the component.
114
115**Atomic service API**: This API can be used in atomic services since API version 11.
116
117**System capability**: SystemCapability.ArkUI.ArkUI.Full
118
119**Parameters**
120
121| Name   | Type                        | Description        |
122|--------|----------------------------|------------|
123| params | { [key: string]: unknown } | Construction parameters of the custom component.|
124
125```ts
126// xxx.ets
127export class Message {
128  value: string | undefined;
129
130  constructor(value: string) {
131    this.value = value
132  }
133}
134
135@Entry
136@Component
137struct Index {
138  @State switch: boolean = true
139
140  build() {
141    Column() {
142      Button('Hello World')
143        .fontSize(50)
144        .fontWeight(FontWeight.Bold)
145        .onClick(() => {
146          this.switch = !this.switch
147        })
148      if (this.switch) {
149        Child({ message: new Message('Child') })
150      }
151    }
152    .height("100%")
153    .width('100%')
154  }
155}
156
157@Reusable
158@Component
159struct Child {
160  @State message: Message = new Message('AboutToReuse');
161
162  aboutToReuse(params: Record<string, ESObject>) {
163    console.info("Recycle Child")
164    this.message = params.message as Message
165  }
166
167  build() {
168    Column() {
169      Text(this.message.value)
170        .fontSize(20)
171    }
172    .borderWidth(2)
173    .height(100)
174  }
175}
176```
177
178## aboutToReuse<sup>18+</sup>
179
180aboutToReuse?(): void
181
182Invoked when a reusable custom component managed by state management V2 is taken from the reuse pool and reinserted into the node tree.
183
184For details, see [\@ReusableV2](../../../quick-start/arkts-new-reusableV2.md).
185
186**Atomic service API**: This API can be used in atomic services since API version 18.
187
188**System capability**: SystemCapability.ArkUI.ArkUI.Full
189
190```ts
191@Entry
192@ComponentV2
193struct Index {
194  @Local condition: boolean = true;
195  build() {
196    Column() {
197      Button('Recycle/Reuse').onClick(()=>{this.condition=!this.condition;}) // Click to switch the recycle/reuse state.
198      if (this.condition) {
199        ReusableV2Component()
200      }
201    }
202  }
203}
204@ReusableV2
205@ComponentV2
206struct ReusableV2Component {
207  @Local message: string = 'Hello World';
208  aboutToReuse() {
209    console.log('ReusableV2Component aboutToReuse'); // Called when a component is reused.
210  }
211  build() {
212    Column() {
213      Text(this.message)
214    }
215  }
216}
217```
218
219
220## aboutToRecycle<sup>10+</sup>
221
222aboutToRecycle?(): void
223
224Invoked when this reusable component is about to be added from the component tree to the reuse cache.
225
226**Atomic service API**: This API can be used in atomic services since API version 11.
227
228**System capability**: SystemCapability.ArkUI.ArkUI.Full
229
230```ts
231// xxx.ets
232export class Message {
233  value: string | undefined;
234
235  constructor(value: string) {
236    this.value = value;
237  }
238}
239
240@Entry
241@Component
242struct Index {
243  @State switch: boolean = true;
244
245  build() {
246    Column() {
247      Button('Hello World')
248        .fontSize(50)
249        .fontWeight(FontWeight.Bold)
250        .onClick(() => {
251          this.switch = !this.switch;
252        })
253      if (this.switch) {
254        Child({ message: new Message('Child') })
255      }
256    }
257    .height("100%")
258    .width('100%')
259  }
260}
261
262@Reusable
263@Component
264struct Child {
265  @State message: Message = new Message('AboutToReuse');
266
267  aboutToReuse(params: Record<string, ESObject>) {
268    console.info("Reuse Child");
269    this.message = params.message as Message;
270  }
271
272  aboutToRecycle() {
273    // This is where you can release memory-intensive content or other non-essential resource references to avoid continuous memory usage that could lead to memory leaks.
274    console.info("The child enters the recycle pool.");
275  }
276
277  build() {
278    Column() {
279      Text(this.message.value)
280        .fontSize(20)
281    }
282    .borderWidth(2)
283    .height(100)
284  }
285}
286```
287
288## onWillApplyTheme<sup>12+</sup>
289
290onWillApplyTheme?(theme: Theme): void
291
292Invoked before the **build()** function of a new instance of the custom component is executed, to obtain the **Theme** object of the component context. You can change state variables in **onWillApplyTheme**. The change will take effect when you execute the **build()** function next time.
293
294> **NOTE**
295>
296> Since API version 18, this API is supported in the components of V2.
297
298**Atomic service API**: This API can be used in atomic services since API version 12.
299
300**System capability**: SystemCapability.ArkUI.ArkUI.Full
301
302**Parameters**
303
304| Name   | Type                                      | Description        |
305|--------|------------------------------------------|------------|
306| theme | [Theme](../js-apis-arkui-theme.md#theme) | Current theme object of the custom component.|
307
308V1:
309
310```ts
311// xxx.ets
312import { CustomTheme, CustomColors, Theme, ThemeControl } from '@kit.ArkUI';
313
314class BlueColors implements CustomColors {
315  fontPrimary = Color.White;
316  backgroundPrimary = Color.Blue;
317  brand = Color.Blue; // Brand color
318}
319
320class PageCustomTheme implements CustomTheme {
321  colors?: CustomColors;
322
323  constructor(colors: CustomColors) {
324    this.colors = colors;
325  }
326}
327const BlueColorsTheme = new PageCustomTheme(new BlueColors());
328// setDefaultTheme should be called on the application entry page or in an ability.
329ThemeControl.setDefaultTheme(BlueColorsTheme);
330
331@Entry
332@Component
333struct IndexComponent {
334  @State textColor: ResourceColor = $r('sys.color.font_primary');
335  @State columBgColor: ResourceColor = $r('sys.color.background_primary');
336
337  // Obtain the Theme object of the current component context. Set textColor and columBgColor in onWillApplyTheme to the color (BlueColorsTheme) of the Theme object in use.
338  onWillApplyTheme(theme: Theme) {
339    this.textColor = theme.colors.fontPrimary;
340    this.columBgColor = theme.colors.backgroundPrimary;
341    console.info('IndexComponent onWillApplyTheme');
342  }
343
344  build() {
345    Column() {
346      // Initial color style of the component
347      Column() {
348        Text('Hello World')
349          .fontColor($r('sys.color.font_primary'))
350          .fontSize(30)
351      }
352      .width('100%')
353      .height('25%')
354      .borderRadius('10vp')
355      .backgroundColor($r('sys.color.background_primary'))
356
357      // The color style configured in onWillApplyTheme is applied.
358      Column() {
359        Text('onWillApplyTheme')
360          .fontColor(this.textColor)
361          .fontSize(30)
362        Text('Hello World')
363          .fontColor(this.textColor)
364          .fontSize(30)
365      }
366      .width('100%')
367      .height('25%')
368      .borderRadius('10vp')
369      .backgroundColor(this.columBgColor)
370    }
371    .padding('16vp')
372    .backgroundColor('#dcdcdc')
373    .width('100%')
374    .height('100%')
375  }
376}
377```
378![onWillApplyThemePage](figures/onWillApplyTheme.png)
379
380V2:
381
382```ts
383import { CustomTheme, CustomColors, Theme, ThemeControl } from '@kit.ArkUI';
384
385class BlueColors implements CustomColors {
386  fontPrimary = Color.White;
387  backgroundPrimary = Color.Blue;
388  brand = Color.Blue; // Brand color
389}
390
391class PageCustomTheme implements CustomTheme {
392  colors?: CustomColors;
393
394  constructor(colors: CustomColors) {
395    this.colors = colors;
396  }
397}
398
399const BlueColorsTheme = new PageCustomTheme(new BlueColors());
400// setDefaultTheme should be called on the application entry page or in an ability.
401ThemeControl.setDefaultTheme(BlueColorsTheme);
402
403@Entry
404@ComponentV2
405struct IndexComponent {
406  @Local textColor: ResourceColor = $r('sys.color.font_primary');
407  @Local columBgColor: ResourceColor = $r('sys.color.background_primary');
408
409  // Obtain the Theme object of the current component context. Set textColor and columBgColor in onWillApplyTheme to the color (BlueColorsTheme) of the Theme object in use.
410  onWillApplyTheme(theme: Theme) {
411    this.textColor = theme.colors.fontPrimary;
412    this.columBgColor = theme.colors.backgroundPrimary;
413    console.info('IndexComponent onWillApplyTheme');
414  }
415
416  build() {
417    Column() {
418      // Initial color style of the component
419      Column() {
420        Text('Hello World')
421          .fontColor($r('sys.color.font_primary'))
422          .fontSize(30)
423      }
424      .width('100%')
425      .height('25%')
426      .borderRadius('10vp')
427      .backgroundColor($r('sys.color.background_primary'))
428
429      // The color style configured in onWillApplyTheme is applied.
430      Column() {
431        Text('onWillApplyTheme')
432          .fontColor(this.textColor)
433          .fontSize(30)
434        Text('Hello World')
435          .fontColor(this.textColor)
436          .fontSize(30)
437      }
438      .width('100%')
439      .height('25%')
440      .borderRadius('10vp')
441      .backgroundColor(this.columBgColor)
442    }
443    .padding('16vp')
444    .backgroundColor('#dcdcdc')
445    .width('100%')
446    .height('100%')
447  }
448}
449```
450
451![onWillApplyTheme_V2](figures/onWillApplyTheme_V2.png)
452