1# \@Watch: Getting Notified of State Variable Changes 2 3 4\@Watch is used to listen for state variables. If your application needs watch for value changes of a state variable, you can decorate the variable with \@Watch. 5 6 7> **NOTE** 8> 9> Since API version 9, this decorator is supported in ArkTS widgets. 10 11 12## Overview 13 14An application can request to be notified whenever the value of the \@Watch decorated variable changes. The \@Watch callback is called when the value change has occurred. \@Watch uses strict equality (===) to determine whether a value is updated in the ArkUI framework. If **false** is returned, the \@Watch callback is triggered. 15 16 17## Decorator Description 18 19| \@Watch Decorator| Description | 20| -------------- | ---------------------------------------- | 21| Decorator parameters | Mandatory. Constant string, which is quoted. Reference to a (string) => void custom component member function.| 22| Custom component variables that can be decorated | All decorated state variables. Regular variables cannot be watched. | 23| Order of decorators | It is recommended that the \@State, \@Prop, \@Link, or other decorators precede the \@Watch decorator.| 24 25 26## Syntax 27 28| Type | Description | 29| ---------------------------------------- | ---------------------------------------- | 30| (changedPropertyName? : string) => void | This function is a member function of the custom component. **changedPropertyName** indicates the name of the watched attribute.<br>It is useful when you use the same function as a callback to several watched attributes.<br>It takes the attribute name as a string input parameter and returns nothing.| 31 32 33## Observed Changes and Behavior 34 351. When a state variable change (including the change of the named attribute in AppStorage or LocalStorage) is observed, the corresponding \@Watch callback is triggered. 36 372. \@The Watch callback is executed synchronously after the variable change in the custom component. 38 393. If the \@Watch callback mutates other watched variables, their variable @Watch callbacks in the same and other custom components as well as state updates are triggered. 40 414. A \@Watch function is not called upon custom component variable initialization, because initialization is not considered as variable mutation. A \@Watch function is called upon updating of the custom component variable. 42 43 44## Restrictions 45 46- Pay attention to the risk of infinite loops. Loops can be caused by the \@Watch callback directly or indirectly mutating the same variable. To avoid loops, avoid mutating the \@Watch decorated state variable inside the callback handler. 47 48- Pay attention to performance. The attribute value update function delays component re-render (see the preceding behavior description). The callback should only perform quick computations. 49 50- Calling **async await** from an \@Watch function is not recommended, because asynchronous behavior may cause performance issues of re-rendering. 51 52 53## Application Scenarios 54 55 56### Combination of \@Watch and \@Link 57 58This example illustrates how to watch an \@Link decorated variable in a child component. 59 60 61```ts 62class PurchaseItem { 63 static NextId: number = 0; 64 public id: number; 65 public price: number; 66 67 constructor(price: number) { 68 this.id = PurchaseItem.NextId++; 69 this.price = price; 70 } 71} 72 73@Component 74struct BasketViewer { 75 @Link @Watch('onBasketUpdated') shopBasket: PurchaseItem[]; 76 @State totalPurchase: number = 0; 77 78 updateTotal(): number { 79 let total = this.shopBasket.reduce((sum, i) => sum + i.price, 0); 80 // A discount is provided when the amount exceeds 100 euros. 81 if (total >= 100) { 82 total = 0.9 * total; 83 } 84 return total; 85 } 86 // @Watch callback 87 onBasketUpdated(propName: string): void { 88 this.totalPurchase = this.updateTotal(); 89 } 90 91 build() { 92 Column() { 93 ForEach(this.shopBasket, 94 (item) => { 95 Text(`Price: ${item.price.toFixed(2)} €`) 96 }, 97 item => item.id.toString() 98 ) 99 Text(`Total: ${this.totalPurchase.toFixed(2)} €`) 100 } 101 } 102} 103 104@Entry 105@Component 106struct BasketModifier { 107 @State shopBasket: PurchaseItem[] = []; 108 109 build() { 110 Column() { 111 Button('Add to basket') 112 .onClick(() => { 113 this.shopBasket.push(new PurchaseItem(Math.round(100 * Math.random()))) 114 }) 115 BasketViewer({ shopBasket: $shopBasket }) 116 } 117 } 118} 119``` 120 121The processing procedure is as follows: 122 1231. **Button.onClick** of the **BasketModifier** component adds an item to **BasketModifier shopBasket**. 124 1252. The value of the \@Link decorated variable **BasketViewer shopBasket** changes. 126 1273. The state management framework calls the \@Watch callback **BasketViewer onBasketUpdated** to update the value of **BaketViewer TotalPurchase**. 128 1294. Because \@Link decorated shopBasket changes (a new item is added), the ForEach component executes the item Builder to render and build the new item. Because the @State decorated totalPurchase variables changes, the **Text** component is also re-rendered. Re-rendering happens asynchronously. 130 131 132### \@Watch and Custom Component Update 133 134This example is used to clarify the processing steps of custom component updates and \@Watch. Note that **count** is @State decorated in both components. 135 136 137```ts 138@Component 139struct TotalView { 140 @Prop @Watch('onCountUpdated') count: number; 141 @State total: number = 0; 142 // @Watch cb 143 onCountUpdated(propName: string): void { 144 this.total += this.count; 145 } 146 147 build() { 148 Text(`Total: ${this.total}`) 149 } 150} 151 152@Entry 153@Component 154struct CountModifier { 155 @State count: number = 0; 156 157 build() { 158 Column() { 159 Button('add to basket') 160 .onClick(() => { 161 this.count++ 162 }) 163 TotalView({ count: this.count }) 164 } 165 } 166} 167``` 168 169Processing steps: 170 1711. The click event **Button.onClick** of the **CountModifier** custom component increases the value of **count**. 172 1732. In response to the change of the @State decorated variable **count**, \@Prop in the child component **TotalView** is updated, and its **\@Watch('onCountUpdated')** callback is triggered, which updates the **total** variable in **TotalView**. 174 1753. The **Text** component in the child component **TotalView** is re-rendered. 176