目录

@Computed Decorator: Declaring Computed Properties

When you use the same computation logic repeatedly bound to the UI, to prevent redundant computation, they can use the @Computed computed property. When the state variables that the computed property depends on change, the computation is performed only once. This resolves the redundant computation and performance issues caused by the UI reusing the property multiple times. See the following example.

@Computed
get sum() {
  return this.count1 + this.count2 + this.count3;
}
Text(`${this.count1 + this.count2 + this.count3}`) // Calculate the sum of three counters.
Text(`${this.count1 + this.count2 + this.count3}`) // Repeat the same calculation.
Text(`${this.sum}`) // Read the cached value from the @Computed sum, avoiding redundant calculations.
Text(`${this.sum}`) // Read the cached value from the @Computed sum, avoiding redundant calculations.

Before reading this topic, it is advised to familiarize yourself with @ComponentV2, @ObservedV2 and @Trace, and @Local.

The @Computed decorator is supported since API version 12.

This decorator can be used in atomic services since API version 12.

This decorator can be used in ArkTS widgets since API version 23.

Overview

@Computed is a method decorator that decorates getter methods. It detects changes in the computed properties and ensures the calculation is performed only once when the properties change. Avoid modifying variables inside @Computed, as incorrect usage may lead to untracked data or application freezes. For details, see Constraints.

For simple calculations, using @Computed is not recommended due to its inherent overhead. For complex computations, @Computed provides significant performance benefits.

Decorator Description

@Computed syntax:

@Computed
get varName(): T {
    return value;
}
@Computed Decorator Description
Supported Type Getter accessor.
Initialization from the parent component Forbidden.
Child component initialization @Param.
Execution time

In @ComponentV2, @Computed is initialized when the custom component is created, triggering computation.

In @ObservedV2 decorated classes, @Computed is initialized asynchronously after the class instance is created, triggering computation.

Recomputation occurs when state variables used in the @Computed calculation are modified.

Value assignment allowed No. @Computed decorated properties are read-only. For details, see Constraints.

Constraints

Use Cases

[h2]The @Computed Decorated Getter is Evaluated Only Once Upon Property Change

  1. Using a computed property in a custom component

    • Clicking the first button changes the value of lastName, triggering a recomputation of the @Computed decorated property fullName.

    • this.fullName is bound to two Text components. The fullName log shows that the computation occurs only once.

    • For the first two Text components, the this.lastName +' '+ this.firstName logic is evaluated twice.

    • If multiple UI elements require the same computed logic this.lastName +' '+ this.firstName, you can use a computed property to reduce redundant calculations.

    • Clicking the second button increments the value of age, but the UI remains unchanged. This is because age is not a state variable, and only changes to observed variables can trigger the recomputation of the @Computed decorated property fullName.

    import { hilog } from '@kit.PerformanceAnalysisKit';
    
    const TAG = '[Sample_Textcomponent]';
    const DOMAIN = 0xF811;
    const BUNDLE = 'Textcomponent_';
    
    @Entry
    @ComponentV2
    struct CustomComponentUse {
      @Local firstName: string = 'Li';
      @Local lastName: string = 'Hua';
      age: number = 20; // Computed cannot be triggered.
    
      @Computed
      get fullName() {
        hilog.info(DOMAIN, TAG, BUNDLE + '---------Computed----------');
        return this.firstName + ' ' + this.lastName + this.age;
      }
    
      build() {
        Column() {
          Text(this.lastName + ' ' + this.firstName)
            .fontSize(20)
            .margin(10)
          Text(this.lastName + ' ' + this.firstName)
            .fontSize(20)
            .margin(10)
          Divider()
          Text(this.fullName)
            .fontSize(20)
            .margin(10)
          Text(this.fullName)
            .fontSize(20)
            .margin(10)
          Button('changed lastName')
            .width(300)
            .margin(10)
            .onClick(() => {
              this.lastName += 'a';
            })
    
          Button('changed age')
            .width(300)
            .margin(10)
            .onClick(() => {
              this.age++;  // Computed cannot be triggered.
            })
        }
      }
    }

    Computed properties inherently introduce performance overhead. In practical development, note the following:

    • For simple logic, avoid computed properties and compute directly.

    • If the logic is used only once in the view, skip the computed property and evaluate inline.

  2. Using a computed property in an @ObservedV2 decorated class

    Clicking the button changes the value of lastName, triggering the @Computed decorated property fullName to recompute once.

    import { hilog } from '@kit.PerformanceAnalysisKit';
    
    const TAG = '[Sample_Textcomponent]';
    const DOMAIN = 0xF811;
    const BUNDLE = 'Textcomponent_';
    
    @ObservedV2
    class Name {
      @Trace public firstName: string = 'Hua';
      @Trace public lastName: string = 'Li';
    
      @Computed
      get fullName() {
        hilog.info(DOMAIN, TAG, BUNDLE + '---------Computed----------');
        return this.firstName + ' ' + this.lastName;
      }
    }
    
    const name: Name = new Name();
    
    @Entry
    @ComponentV2
    struct ObservedV2ClassUser {
      name1: Name = name;
    
      build() {
        Column() {
          Text(this.name1.fullName)
            .fontSize(20)
            .margin(10)
          Text(this.name1.fullName)
            .fontSize(20)
            .margin(10)
          // Tap the Button to change lastName, triggering fullName recomputation. The value is computed only once.
          Button('changed lastName')
            .width(300)
            .margin(10)
            .onClick(() => {
              this.name1.lastName += 'a';
            })
        }
        .width('100%')
      }
    }

[h2]@Monitor Can Listen for the Changes of the @Computed Decorated Properties

The following example shows how to convert celsius to fahrenheit and kelvin Example:

[h2]@Computed Decorated Properties Can Initialize @Param

The following example shows how to use an @Computed decorated property to initialize @Param.