In the declarative UI programming paradigm, the UI is a function of an app state, and a modification of the app state updates a corresponding UI. ArkUI uses the MVVM mode, in which ViewModel binds data and views and directly updates views when data is updated, as shown in the following figure.

ArkUI provides a series of decorators to implement ViewModel capabilities, such as @Prop: Implementing One-Way Synchronization from Parent to Child Components, @Link Decorator: Two-Way Synchronization Between Parent and Child Components, @Provide and @Consume Decorators: Two-Way Synchronization with Descendant Components, and LocalStorage: Storing Page-Level UI State. When a variable in a custom component is decorated by a decorator, the variable becomes a state variable. The change of the state variable causes the UI rendering to be refreshed.
During ArkUI development, if a proper decorator is not selected or the state update range is not properly controlled, the following problems may occur:
1. A state is inconsistent with that on the UI. For example, UI elements in the same state are displayed on different UIs, or the state displayed on the UI is not the latest.
2. Unnecessary UI view refresh occurs. For example, if only the state of a partial component is changed, the whole page where the component resides is refreshed.
When a user interacts with the GUI, the state change is driven by events. Events can be processed anywhere in the app. Improper logic processing and management will result in redundant code and difficult maintenance.
This topic aims to solve the preceding problems in terms of decorator selection, use, and state logic processing and management to achieve better state management.
Deleting Redundant State Variable Flags
The management of state variables will cause certain overhead and should be conducted in proper scenarios. Common variables marked with state variables may cause performance deterioration.
Negative example 1:
@Observed
class Translate {
translateX: number = 20;
}
@Component
struct MyComponent {
@State translateObj: Translate = new Translate(); // The variable translateObj is not associated with any UI component and should not be defined as a state variable
@State buttonMsg: string = 'I am button'; // The variable buttonMsg is not associated with any UI component and should not be defined as a state variable
build() {
}
} In the preceding example, the translateObj and buttonMsg variables are not associated with any UI component. These variables should not be defined as state variables. Otherwise, the performance will be compromised when they are read or written.
You are advised to use the Code Linter scanning tool for code inspection, focusing specifically on the @performance/hp-arkui-remove-redundant-state-var rule. If issues related to this rule are identified in the scan results, adjust your code by following the optimization suggestions provided in this section.
Negative example 2:
@Observed
class Translate {
translateX: number = 20;
}
@Component
struct MyComponent {
@State translateObj: Translate = new Translate();
@State buttonMsg: string = 'I am button';
build() {
Column() {
Button(this.buttonMsg) // Here we just read the value of the variable buttonMsg, without any write operation.
}
}
} In the preceding example, the buttonMsg variable is only read but never modified. Unmodified variables should not be declared as state variables, as unnecessary state tracking during read operations introduces performance overhead.
You are advised to use the Code Linter scanning tool for code inspection, focusing specifically on the @performance/hp-arkui-remove-unchanged-state-var rule. If issues related to this rule are identified in the scan results, adjust your code by following the optimization suggestions provided in this section.
Positive example:
@Observed
class Translate {
translateX: number = 20;
}
@Component
struct UnnecessaryState1 {
@State translateObj: Translate = new Translate(); // If there are both read and write operations and a Button component is associated with it, it is recommended to use state variables.
buttonMsg = 'I am button'; // Only read the value of the variable buttonMsg, without any write operations, just use the general variables directly
build() {
Column() {
Button(this.buttonMsg)
.onClick(() => {
this.getUIContext().animateTo({
duration: 50
}, () => {
this.translateObj.translateX = (this.translateObj.translateX + 50) % 150; // Reassign value to variable translateObj when clicked.
})
})
}
.translate({
x: this.translateObj.translateX // Retrieve the value in translateObj.
})
}
} In the code, the buttonMsg variable is defined as a common member variable because it is used only for read operations. The translateObj variable is defined as a state variable because its x value needs to be changed based on user events to drive the animation effect. The UI is re-rendered in real time to display the animation.
Using Temporary Variables Instead of State Variables
When a state variable changes, ArkUI queries the components that require the state variable and executes an update method to render the components. However, by computing the temporary variables instead of directly changing the state variables, ArkUI can query and render components only when the last state variable changes, which reduces unnecessary behaviors and improves app performance. For details about the behavior of state variables, see @State Decorator: State Owned by Component.
Negative example:
@Component
struct Index {
@State message: string = '';
// Define methods for changing state variables (multiple modifications of state variables)
appendMsg(newMsg: string) {
this.message += newMsg;
this.message += ';';
this.message += '<br/>';
}
build() {
Column() {
Button('Click Print Log')
.onClick(() => {
this.appendMsg('Operational state variables'); // Calling encapsulated methods for changing state variables
})
.width('90%')
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.margin({ top: 10})
}
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Center)
.margin({ top: 15 })
}
} Positive example:
@Entry
@Component
struct UnnecessaryState2 {
@State message: string = '';
// Define methods for changing state variables (intermediate variables are manipulated during method execution, state variables are modified only once)
appendMsg(newMsg: string) {
let message = this.message;
message += newMsg;
message += ';';
message += '<br/>';
this.message = message;
}
build() {
Column() {
Button('Click Print Log')
.onClick(() => {
this.appendMsg('Manipulating Temporary Variables'); // Calling encapsulated methods for changing state variables
})
.width('90%')
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.margin({ top: 10 })
}
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Center)
.margin({ top: 15 })
}
} In the absence of strong service requirements, select a proper decorator based on the minimum scope of states to be shared. During app development, states are classified into intra-component exclusive states and inter-component shared states based on the component granularity.
Intra-Component Exclusive States
The lifecycle of an exclusive state in a component is the same as that of the component. The state is defined and updated in the component. When the component is destroyed, the state disappears accordingly. Intra-component exclusive states are commonly used for UI element data, such as whether the current button is available and whether the text is highlighted. @State decorator is used for exclusive states in a component. The modification of a state decorated by @State triggers the re-rendering of the current component instance only. As shown in the following figure, @State is used to modify the variable indicating whether a theme is selected in a single theme component. When a theme is tapped on the UI, the state value is directly changed in the component. In this case, only the component instance of the current theme is re-rendered. Other theme components are not re-rendered.

Inter-Component Shared States
For the states to be shared between components, there are three scenarios in ascending order of the sharing scope: sharing states between parent and child components; sharing states between components in different subtrees; and sharing states between different component trees.



For the preceding three scenarios, ArkUI provides six decorator combinations: @State+@Prop, @State+@Link, @State+@Observed+@ObjectLink, @Provide+@Consume, AppStorage, and LocalStorage, to share states among components in different scopes. Based on the sharing scope capability in ascending order, the sharing scope capability and lifecycle of each decorator combination are as follows:
According to software development principles, decorators with a limited sharing scope should be prioritized to reduce unnecessary parameter passing through layers, decrease data coupling between different modules, and facilitate timely state recycling. You are advised to select the following decorators in priority: @State+@Prop, @State+@Link, and @State+@Observed+@ObjectLink > @Provide+@Consume > LocalStorage > AppStorage.
When decorators are selected based on the preceding priorities, the @State+@Prop, @State+@Link, and @State+@Observed+@ObjectLink solutions transfer a state level by level. When the levels of components that share states differ greatly, the state is transferred layer by layer. For all components involved in state transfer, input parameters need to be added to receive the state and then transfer the state to child components. For an intermediate component that does not use this state, this is "extra consumption", which is not conducive to code maintenance and expansion. Especially when the service system is large, requirement changes may impact on the whole system.
Take the route state in HMOS World App as an example. The following figure shows the components on the Discover and Mine tab pages.


In the project, the Navigation component is used to manage routes. The appNavigationStack variable indicates the current routing information of the app. The DiscoverView and ResourceListView components need to share the state of the routing information. According to the layer-by-layer transfer solution in the @State+@Prop scenario, the design of each component is as follows:

As shown in the figure, to enable the ResourceListView and DiscoverView components to share a state, the state is defined in the MainPage component, which is the closest common ancestor of the two components. The @Prop decorator is used to receive the appNavigationStack parameter for all components on the path from the common ancestor to the two components that need to share the routing state. The parameter is transferred layer by layer to the two target components.
If a new function is required, the logic for determining routing information must be added to the ActionButtonView component, which is a descendant of the DiscoverView component. In this case, you need to modify the design of the preceding components, as shown in the following figure.

As shown in the figure, the logic of the new function is originally used only in the ActionButtonView component. However, you need to modify the structure of the three components on the path from the DiscoverView component to the ActionButtonView component. If the service does not need to use the state again, you also need to modify multiple components. Obviously, this is not a good implementation solution.
In this case, the @Provide+@Consume solution is more feasible. The ResourceListView and DiscoverView components share the same state. The components in this solution are designed as follows:

After the routing information state whose key value is appNavigationStack is injected to the top MainPage component, the descendants of the component can obtain the state value through the @Consume decorator. When the service change requires the ActionButtonView component, a descendant of the DiscoverView component, to share routing information, this solution only needs to use the @Consume decorator on the ActionButtonView component to directly obtain the routing information state without modifying other components. In this case, the components are designed as follows:

Therefore, when the components that share the state differ much in layers, or the shared information exists globally for the entire component tree, the @Provide+@Consume decorator combination is used to replace the layer-by-layer transfer mode, which can improve the maintainability and scalability of the code.
The @State+@Prop, @State+@Link, and @State+@Observed+@ObjectLink solutions are selected for the preceding decorators with the same priority. When selecting a solution, you need to consider the specific service scenario and the complexity of the state data structure. The three decorator combinations offer different capabilities with regard to memory consumption, performance deterioration, and data type, as shown in the following figure.

Based on the features of the three solutions, the following suggestions are provided:
In actual development, select proper decorators in the following three steps:
1. Select the decorator solution with the minimum sharing capability based on the sharing scope in priority: @State+@Prop, @State+@Link, or @State+@Observed+@ObjectLink > @Provide+@Consume > LocalStorage > AppStorage.
2. If the levels of components that share the state differ greatly, the @Provide+@Consume solution is better than the layer-by-layer sharing solution to avoid poor code scalability and maintainability.
3. For the @State+@Prop, @State+@Link, or @State+@Observed+@ObjectLink solutions with the same priority, select a solution based on the state complexity and the features of the decorators.
In actual development, you need to select proper decorators based on the service requirements subject to the following suggestions:
AppStorage boasts the widest application scope. To facilitate development, you can easily store various states in AppStorage for sharing, which usually results in a large amount of performance loss.
This is because the state modification and refresh in ArkUI are coarse-grained. If the decorator is used to modify a state of the object type, ArkUI can listen to the changes of the object value and the object property value. After the value of an object property changes, ArkUI notifies all components that use the property to re-render the property based on the entire object granularity instead of the property granularity.
To illustrate how to use AppStorage, the following uses the shared user information and user favorite information in HMOS World App as an example to describe how to split the state storage. The modules and UIs involved in user information and user favorites information are presented in the following.


In the current project, AppStorage has been used to store user data (UserData). The data structure of UserData and the code for the UserInfoView component to display user data in the UserData state are as follows:
// Data structure of user information UserData
export interface UserData {
id: string;
username: string;
description: string;
// ...
}
// ...
// Getting server-side user information in a business class
getUserData(): void {
this.userAccountRepository.getUserData().then((data: UserData) => {
// 1.Storing user information data into AppStorage
AppStorage.setOrCreate('userData', data);
});
}
// ...
// View component for displaying user information at the top of the "My" module
@Component
struct UserInfoView {
// 2.Receive user information stored in AppStorage using @StorageLink decorator in UI
@StorageLink('userData') userData: UserData | null = null;
build() {
Column() {
Row() {
// ...
Column() {
// 3.Display the user name in the userData.
Text(this.userData ? this.userData.username : 'default_login')
// ...
}
}
// ...
}
// ...
}
} Now, the Discover and Mine modules need to share the favorites list data of a user. Only the ID array of the articles in favorites needs to be shared. The state sharing among different modules is also stored in AppStorage. The following two storage solutions are available:
1. The favorites data is a part of the user data. In this case, the favorites data is used as a property of the user data (userData) and is stored in the variable whose key value is userData in the current AppStorage.
2. The favorites data is stored in AppStorage separately and is not bound to userData.
The code implementation of the first solution is as follows:
export interface UserData {
id: string;
username: string;
description: string;
// 1. Add a list of resources in the user's collection on the user information UserData id Information Type Definition
collectedIds: string[];
// ...
}
// ...
// Getting server-side user information in a business class
getUserData(): void {
this.userAccountRepository.getUserData().then((data: UserData) => {
// 2.Storing user information data into AppStorage
AppStorage.setOrCreate('userData', data);
})
}
// ...
// Article card component of the Explore module
@Component
export struct ArticleCardView {
// 3.Get the user information object userData on the ExploreArticleList card with the @StorageLink decorator
@StorageLink('userData') userData: UserData | null = null;
@Prop articleItem: LearningResource = new LearningResource();
// 4.Calculate whether the current article is favorite or not according to the favorite information array
isCollected(): boolean {
return !!this.userData && this.userData.collectedIds.some((id: string) => id === this.articleItem.id);
}
// 7.Handling interface like interaction logic: when the userData state sub-property collectedIds received using the @StorageLink decorator is modified, the new value is synchronized to AppStorage
handleCollected(): void {
// ...
const index = this.userData?.collectedIds.findIndex((id: string) => id === this.articleItem.id) as number;
if (index === -1) {
this.userData?.collectedIds.push(resourceId);
} else {
this.userData?.collectedIds.splice(index, 1);
}
// ...
}
build() {
ActionButtonView({
// 5.Determine whether the favorite icon is highlighted according to whether the current article has been favorited by the user or not
imgResource: this.isCollected() ? $r('app.media.icon') : $r('app.media.icon'),
count: this.articleItem.collectionCount,
textWidth: 77
})
.onClick(() => {
// 6.When the user clicks on the favorites icon, the function that handles changes to the status of the favorites is called
this.handleCollected();
})
}
} In this solution, after a user modifies the value of userData.description on the UserInfoView component, the modification is synchronized to AppStorage. ArkUI detects the change of the value whose key value is userData in AppStorage and notifies all components that use the key value userData in AppStorage to perform rendering again.
On the preceding UI, the UserInfoView component that displays user data in the Mine module is rendered again. The article widget component ArticleCardView of the Discover module is bound to the variable whose key value is userData in AppStorage through the @StorageLink decorator. Therefore, all article widget components are rendered again. These components are irrelevant to the user description and should not be compromised by the modification of the description. As a result, the rendering is refreshed.
Use the second solution. The code is as follows:
// Getting user information in a business class
getUserData(): void {
this.userAccountRepository.getUserData().then((data: UserData) => {
//1.Separate storage of user collection information data in AppStorage
AppStorage.setOrCreate('collectedIds', data.collectedIds);
AppStorage.setOrCreate('userData', data);
})
}
// Article card component of the Explore module
@Component
export struct ArticleCardView {
// 2.Getting collection information stored in AppStorage via @StorageLink decorator
@StorageLink('collectedIds') collectedIds: string[] = [];
@Prop articleItem: LearningResource = new LearningResource();
// 3.Calculate whether the current article is favorite or not according to the favorite information array
isCollected(): boolean {
return this.collectedIds.some((id: string) => id === this.articleItem.id);
}
// 6.Handling interface like interaction logic: when the state collectedIds received using the @StorageLink decorator are modified, the new values are synchronized to AppStorage
handleCollected(): void {
// ...
const index = this.collectedIds.findIndex((id: string) => id === this.articleItem.id);
if (index === -1) {
this.collectedIds.push(resourceId);
} else {
this.collectedIds.splice(index, 1);
}
// ...
}
build(){
ActionButtonView({
// 4.Determine whether the favorite icon is highlighted according to whether the current article has been favorited by the user or not
imgResource: this.isCollected() ? $r('app.media.icon') : $r('app.media.icon'),
count: this.articleItem.collectionCount,
textWidth: 77
})
.onClick(() => {
// 5.When the user clicks on the favorites icon, the function that handles changes to the status of the favorites is called
this.handleCollected();
})
}
} In this solution, the article widget component is not bound to the variable whose key value is userData in AppStorage. After a user modifies the value of userData.description, the article widget component is not rendered again.
In addition, when the user taps the favorites button on the article widget to change the article favorites state, the change is synchronized back to the variable whose key value is collectedIds in AppStorage. After detecting that the value of the key variable in AppStorage is collectedIds, ArkUI notifies all components that are bound to the key variable in AppStorage to re-render the value. The UserInfoView component in the Mine module is not re-rendered.
Therefore, from the perspective of performance, when the LocalStorage or AppStorage decorator is used to store state variables, the state data structure needs to be properly designed to avoid unnecessary rendering and refreshing.
Excessive state structure splitting may lead to overdesign of components in some scenarios, which is not conducive to maintenance. In this case, you can aggregate several properties that are frequently changed on an object or class into a new object or class model, use the @Observed decorator to modify the model, and mount the model to the previous object or class as properties. With this method, ArkUI notifies only the new object or class rather than the top-layer object of the property change. In this way, unnecessary rendering attempts can be effectively reduced, and the code can be better maintained.
For example, properties b, c, and d exist in Class A. Properties c and d often change together. That is, when the state of property c is changed, the state of property d also needs to be changed.
class ClassA{
b: string;
c: number;
d: boolean;
} In this case, properties c and d are combined as a property of the new class ClassE and are decorated by the @Observed decorator. For ClassA, properties c and d are deleted, and property e is added and its type is ClassE type subject to the following design:
class ClassA{
b: string;
e: ClassE;
}
@Observed
class ClassE{
c: number;
d: boolean;
} In this solution, variables whose data structure is ClassA are stored in AppStorage. When the value of property c in property e of the ClassA instance changes, the ArkUI frame notifies the component that uses the ClassE instance of re-rendering, but does not notify all components that use the ClassA instance in AppStorage of the update. That is, the component that uses only the property b of the ClassA instance is not rendered again.
When using the @Link decorator, you can modify a state directly inside a component that receives the state from this decorator. If the logic for modifying the state of multiple child components is similar, it is recommended that the state be modified in a single function to improve the reusability of the logic as well as the maintainability and testability of the code.
For example, when you tap the information widget, article widget, or top image in-turn playback on the home page of the Discover module of HMOS World App, the details page is displayed. The interaction effect is as follows:

The preceding three components share the global routing data. When a user taps the interaction button on the UI, the logic of the three components is to modify the routing state based on the device information to redirect to the details page. This logic is integrated to the parent component for processing the redirection. The sample code is as follows:
@Component
export struct DiscoverView {
private jumpList = () => {
}
@State hotFeedList: never[] = [];
@State articlesDataSource: never[] = [];
@State discoverModel: GeneratedTypeLiteralInterface_1 = { swiperData: [] };
// 1.Getting shared state related to jump logic
@Consume('appPathStack') appPathStack: NavPathStack;
@Consume('discoverPathStack') discoverPathStack: NavPathStack;
@StorageProp('currentBreakpoint') currentBreakpoint: string = 'BreakpointTypeEnum.MD';
// 5.Centralize the jump processing logic of the 3 components in the parent component
jumpDetail(item: LearningResource): void {
if (this.currentBreakpoint === 'BreakpointTypeEnum.LG') {
this.discoverPathStack.pushPathByName('articleDetail', item);
} else {
this.appPathStack.pushPathByName('articleDetail', item);
}
}
build() {
Column() {
List() {
ListItem() {
BannerView({
swiperData: this.discoverModel.swiperData,
// 2.The top rotator component passes in the parent component's logic handler function
handleClick: (item: LearningResource) => this.jumpDetail(item)
})
}
ListItem() {
Column({ space: CommonConstants.SPACE_12 }) {
HotFeedsView({
hotFeedList: this.hotFeedList,
showMore: this.jumpList,
// 3.Information list component passes in the logic handler function of the parent component
handleClick: (item: LearningResource) => this.jumpDetail(item)
})
TechArticlesView({
articlesDataSource: this.articlesDataSource,
// 4.Logic handler function passed to parent component by technical article component
handleClick: (item: LearningResource) => this.jumpDetail(item)
})
}
}
}
}
}
}
@Component
struct BannerView {
@Prop swiperData: LearningResource[] = [];
private swiperController: SwiperController = new SwiperController();
// 6.The rotatoire component receives the logic handler passed to it by the parent component.
handleClick: (item: LearningResource) => void = () => {
};
build() {
Swiper(this.swiperController) {
ForEach(this.swiperData, (item: LearningResource) => {
Row() {
// $r('app.media.icon') needs to be replaced with the resource file required by the developer
Image($r('app.media.icon'))
.width(55)
.height(55)
// Set the border radius to 5 vp.
.borderRadius($r('app.float.component_radius'))
// 7.When clicking on an image, call the received function to process the logic
.onClick(() => this.handleClick(item))
}
// ...
}, (item: LearningResource) => item.id)
}
// ...
}
} The preceding text shows that: By promoting the similar logic of the child component to the parent component for centralized processing, only one copy of the same logic code needs to be written. Otherwise, you need to write a copy of redirection logic processing code for the BannerView, HotFeedsView, and TechArticlesView components. When the service logic changes, you only need to modify the jumpDetail function. During development, the UI logic can be processed on the UI, and the service logic can be extracted into a single file for centralized processing. The UI and data are decoupled to facilitate logic reuse. Proper centralized processing of logic can effectively improve the maintainability and reusability of code.
When multiple components depend on different properties of an object, all components are refreshed upon changes to any property if the object is directly associated. You can split and combine the properties in a class into a new class to accurately control component refreshing.
When multiple components depend on the same data source and are updated based on changes to the data source, directly associating with the data source will cause all components to be updated each time the data source changes. The following policies can be used to precisely control component updates.
Use the @Watch decorator in components to listen to data sources. When the data changes, the service logic is executed to ensure that only the components that meet the criteria are updated.
You are advised to use the Code Linter scanning tool for code inspection, focusing specifically on the @performance/multiple-associations-state-var-check rule. If issues related to this rule are identified in the scan results, adjust your code by following the optimization suggestions provided in this section.
Negative example:
In the following sample code, multiple components are directly associated with the same data source, but the @Watch decorator and Emitter event are not used for update, resulting redundant component updates.
@Component
struct Index {
@State currentIndex: number = 0; // The subscript of the currently selected list item
private listData: string[] = [];
aboutToAppear(): void {
for (let i = 0; i < 10; i++) {
this.listData.push(`${i}`);
}
}
build() {
Row() {
Column() {
List() {
ForEach(this.listData, (item: string, index: number) => {
ListItem() {
ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
}
})
}
.alignListItem(ListItemAlign.Center)
}
.width('100%')
}
.height('100%')
}
}
@Component
struct ListItemComponent {
@Prop item: string;
@Prop index: number; // The subscript of the list item
@Link currentIndex: number;
private sizeFont: number = 50;
isRender(): number {
console.info(`ListItemComponent ${this.index} Text is rendered`);
return this.sizeFont;
}
build() {
Column() {
Text(this.item)
.fontSize(this.isRender())// Dynamically set the color of the text according to the difference between the index and currentIndex of the current list item.
.fontColor(Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue)
.onClick(() => {
this.currentIndex = this.index;
})
}
}
} In the preceding example, each ListItemComponent component assigns the index of the currently tapped list item to currentIndex after Text is tapped. After the state variable currentIndex decorated by @Link changes, the Index values of the parent component and all ListItemComponent components change accordingly. Then, in all ListItemComponent components, the text color is determined based on whether the absolute value of the difference between the subscript index of the list item and the currentIndex property is less than or equal to 1. If the difference is less than or equal to 1, the text is displayed in red. Otherwise, the text is displayed in blue. The following figure shows the running effect.

As shown in the figure, all Text components are refreshed even if the colors of some Text components do not change after each tap. This is because the Text component in the ListItemComponent component is directly associated with the currentIndex property instead of the color calculated based on the currentIndex property.
In the preceding scenario regarding the parent-child component hierarchy, you are advised to use the state decorator @Watch to listen for the data source. When the data source changes, the service logic is executed in the listening callback of @Watch. The component is associated with the callback processing result instead of the data source.
Positive example:
The following describes how to use the @Watch decorator to implement precise refresh.
@Entry
@Component
struct UseWatchListener {
@State currentIndex: number = 0; // The subscript of the currently selected list item
private listData: string[] = [];
aboutToAppear(): void {
for (let i = 0; i < 10; i++) {
this.listData.push(`${i}`);
}
}
build() {
Row() {
Column() {
List() {
ForEach(this.listData, (item: string, index: number) => {
ListItem() {
ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
}
})
}
.height('100%')
.width('100%')
.alignListItem(ListItemAlign.Center)
}
.width('100%')
}
.height('100%')
}
}
@Component
struct ListItemComponent {
@Prop item: string;
@Prop index: number; // The subscript of the list item
@Link @Watch('onCurrentIndexUpdate') currentIndex: number;
@State color: Color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
isRender(): number {
console.info(`ListItemComponent ${this.index} Text is rendered`);
return 50;
}
onCurrentIndexUpdate() {
// Dynamically modifies the value of color based on the difference between the index and currentIndex of the current list item.
this.color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
}
build() {
Column() {
Text(this.item)
.fontSize(this.isRender())
.fontColor(this.color)
.onClick(() => {
this.currentIndex = this.index;
})
}
}
} In the preceding code, the state variable currentIndex in the ListItemComponent component is decorated by @Watch, and the Text component is directly associated with the new state variable color. When the value of currentIndex changes, the onCurrentIndexUpdate method is triggered to assign the expression operation result to the state variable color. The Text component is re-rendered only when the value of color changes. The following figure shows the running effect.

If the data source depended on is transferred only in a parent-child or sibling component, you can use the @State, @Link or @Watch decorator to manage the state and accurately refresh the component.
If there are many component levels but all components belong to the same component tree, you are advised to use @Provide or @Consume to transfer data, use the @Watch decorator to listen for data changes, and execute service logic in the listening callback.
When a component relationship is complex or a component crosses many layers, you are advised to use the EventHub or Emitter custom event release and subscription mode. When a data source changes, an event is released. Components that depend on the data source obtain the data source change by subscribing to the event and process the service logic. In this way, the components can be accurately updated.
The following uses some sample code as an example to describe how to use this method. The ButtonComponent component functions as an interaction component to trigger data changes, and the ListItemComponent component receives data to refresh the UI.
import { ButtonComponent } from '../segment/segment13';
import { ListItemComponent } from '../segment/segment14';
@Entry
@Component
struct UseEmitterPublish {
listData: string[] = ['A', 'B', 'C', 'D', 'E', 'F'];
build() {
Column() {
Row() {
Column() {
ButtonComponent()
}
}
Column() {
Column() {
List() {
ForEach(this.listData, (item: string, index: number) => {
ListItemComponent({ myItem: item, index: index })
})
}
.height('100%')
.width('100%')
.alignListItem(ListItemAlign.Center)
}
}
}
}
} The relationship between the ButtonComponent and ListItemComponent components is complex. Therefore, in the Button callback of the ButtonComponent component, you can use emitter.emit to send events and subscribe to events in the ListItemComponent component. The data value is received in the callback triggered by the event. The service logic determines whether to modify the state variable color to accurately control the Text update in the ListItemComponent component.
import { emitter } from '@kit.BasicServicesKit';
const CHANGE_COLOR_EVENT_ID = 1;
@Component
export struct ButtonComponent {
value: number = 2;
build() {
Button (`The component text whose subscript is a multiple of ${this.value} turns red.`)
.onClick(() => {
let event: emitter.InnerEvent = {
eventId: CHANGE_COLOR_EVENT_ID,
priority: emitter.EventPriority.LOW
};
let eventData: emitter.EventData = {
data: {
value: this.value
}
};
// Sends an event with eventId of CHANGE_COLOR_EVENT_ID and event content of eventData
emitter.emit(event, eventData);
this.value++;
})
}
} import { emitter } from '@kit.BasicServicesKit';
const CHANGE_COLOR_EVENT_ID = 1;
@Component
export struct ListItemComponent {
@State color: Color = Color.Black;
@Prop index: number;
@Prop myItem: string;
aboutToAppear(): void {
let event: emitter.InnerEvent = {
eventId: CHANGE_COLOR_EVENT_ID
};
// Execute this callback after receiving an event with eventId of CHANGE_COLOR_EVENT_ID
let callback = (eventData: emitter.EventData): void => {
if (eventData.data?.value !== 0 && this.index % eventData.data?.value === 0) {
this.color = Color.Red;
}
};
// Subscribe to events with eventId of CHANGE_COLOR_EVENT_ID
emitter.on(event, callback);
}
build() {
Column() {
Text(this.myItem)
.fontSize(50)
.fontColor(this.color)
}
}
} State management is complex in the MVVM mode. To address the issues concerning state and view consistency, rendering performance experience, code reusability, and maintainability, this document provides the following suggestions: