1# State Management Overview
2
3
4In previous examples, most of the pages built are static pages, which are delivered to the end user without having to be processed. If you are building dynamic, interactive pages, you need to master state management.
5
6
7  **Figure 1** State managed UI
8
9![Video_2023-03-06_152548](figures/Video_2023-03-06_152548.gif)
10
11
12In the preceding example, the interaction between the user and the application triggers an update in the text state, which in turn triggers re-rendering of the UI. As a result, the **Hello World** text changes to **Hello ArkUI**.
13
14
15In the declarative UI framework, the UI is the execution result of the application state. You build a UI model in which the application runtime state is a parameter. When the parameter is changed, the UI as the return result is updated accordingly. This process of UI re-rendering caused by the application runtime state changes is called the state management mechanism in ArkUI.
16
17
18Custom components have variables. A variable must be decorated by a decorator whenever the re-rendering of the UI depends on this variable. Otherwise, the UI is rendered only at initialization and will not be updated. The following figure shows the relationship between the state and view (UI).
19
20
21![en-us_image_0000001562352677](figures/en-us_image_0000001562352677.png)
22
23
24- View (UI): UI rendering, which is visual representation of the UI description in the **build** method and \@Builder decorated method.
25
26- State: data that drives the UI to re-render. State data is changed by invoking the event method of the component. The change of the state data triggers the re-rendering of the UI.
27
28
29## Basic Concepts
30
31- State variable: a variable decorated by a state decorator. Its value change will trigger UI re-renders. Example: @State num: number = 1, where @State is a state decorator and **num** is a state variable.
32
33- Regular variable: a variable that is not decorated by a state decorator and is usually used for auxiliary calculation. Its value change will not trigger UI re-renders. In the following example, the **increaseBy** variable is a regular variable.
34
35- Data source/Synchronization source: original source of a state variable, which can be synchronized to different state data. Generally, it is the data passed from the parent component to the child component. In the following example, the data source is **count: 1**.
36
37- Named parameter mechanism: a mechanism where the parent component passes state variables to the child component by specifying parameters. It is the primary means of passing synchronization parameters from the parent component to the child component. Example: **CompA({ aProp: this.aProp })**.
38
39- Initialization from the parent component: a process where the parent component uses the named parameter mechanism to pass specified parameters to the child component. The default value used in local initialization will be overwritten by the value passed from the parent component. Example:
40
41  ```ts
42  @Component
43  struct MyComponent {
44    @State count: number = 0;
45    private increaseBy: number = 1;
46
47    build() {
48    }
49  }
50
51  @Entry
52  @Component
53  struct Parent {
54    build() {
55      Column() {
56        // Initialization from the parent component: The named parameter specified here will overwrite the default value defined locally.
57        MyComponent({ count: 1, increaseBy: 2 })
58      }
59    }
60  }
61  ```
62
63- Child component initialization: a capability to pass state variables to the child component to initialize the corresponding state variables therein. The example is the same as above.
64
65- Local initialization: a process where a value is assigned to a variable as its default value in the variable declaration. Example: \@State count: number = 0.
66
67>**NOTE**
68>
69>Currently, the state management can be used only in the UI main thread and cannot be used in subthreads, Worker, or TaskPool.
70
71
72## State Management (V1)
73
74You can develop applications in the state management of V1.
75
76### Decorator Overview
77
78ArkUI state management V1 provides a diverse array of decorators. You can use these decorators to observe state variables changes within a component or globally and pass the changes between different component levels (for example, between parent and child components or grandparent and grandchild components). According to the scope of the state variable, decorators can be roughly classified into the following types:
79
80
81- Decorators for managing the state of a component: implement state management at the component level by allowing for observation of state changes within a component and changes at different component levels. The observation is limited to state changes in the same component tree, that is, on the same page.
82
83- Decorators for managing the state of an application: implement global state management of an application by allowing for observation of state changes on different pages or even different UIAbility components.
84
85
86According to the data transfer mode and synchronization type, decorators can also be classified into the following types:
87
88
89- Decorators that allow for one-way (read-only) transfer
90
91- Decorators that allow for two-way (mutable) transfer
92
93
94The following figure illustrates the decorators. For details, see [Component State Management](arkts-state.md) and [Application State Management](arkts-application-state-management-overview.md). You can use these decorators at your disposal to implement linkage between data and the UI.
95
96
97![en-us_image_0000001502704640](figures/en-us_image_0000001502704640.png)
98
99
100In the preceding figure, the decorators in the Components area are used for state management at the component level, while others are used for state management at the application level. You can use [@StorageLink](arkts-appstorage.md#storagelink) or [@LocalStorageLink](arkts-localstorage.md#localstoragelink) to implement two-way synchronization of the application and component state, and [@StorageProp](arkts-appstorage.md#storageprop) or [@LocalStorageProp](arkts-localstorage.md#localstorageprop) to implement one-way synchronization.
101
102
103Decorators for [component state management](arkts-state.md):
104
105
106- [\@State](arkts-state.md): An \@State decorated variable holds the state of the owning component. It can be the source of one- or two-way synchronization with child components. When the variable changes, the dependent component will be updated.
107
108- [\@Prop](arkts-prop.md): An \@Prop decorated variable can create one-way synchronization with a variable of its parent component. \@Prop decorated variables are mutable, but changes are not synchronized to the parent component.
109
110- [\@Link](arkts-link.md): An \@Link decorated variable creates two-way synchronization with a variable of its parent component. When the @Link decorated variable has its value changed, its source is updated as well; when the source updates, the @Link decorated variable will do as well.
111
112- [\@Provide/\@Consume](arkts-provide-and-consume.md): Variables decorated by \@Provide/\@Consume are used for data synchronization across component levels. The components can be bound to the variables through aliases or attribute names. Data does not need to be passed through the named parameter mechanism.
113
114- [\@Observed](arkts-observed-and-objectlink.md): \@Observed is a class decorator. You can use it to decorate the class that has multiple levels of nested objects or arrays to be observed. Note that \@Observed must be used with \@ObjectLink for two-way synchronization or with \@Prop for one-way synchronization.
115
116- [\@ObjectLink](arkts-observed-and-objectlink.md): An \@ObjectLink decorated variable is used with an \@Observed decorated class of the parent component for two-way data synchronization. It is applicable in scenarios involving multiple levels of nested objects or arrays in the class.
117
118> **NOTE**
119>
120> Only [\@Observed/\@ObjectLink](arkts-observed-and-objectlink.md) can be used to observe changes of nested attributes. Other decorators can be used to observe changes of attributes at the first layer only. For details, see the "Observed Changes and Behavior" part in each decorator section.
121
122
123Decorators for [application state management](arkts-application-state-management-overview.md):
124
125
126- [AppStorage](arkts-appstorage.md): a special [LocalStorage](arkts-localstorage.md) singleton instance. It is an application-wide database bound to the application process and can be linked to components through the [@StorageProp](arkts-appstorage.md#storageprop) and [@StorageLink](arkts-appstorage.md#storagelink) decorators.
127
128- AppStorage is the hub for application state. Data that needs to interact with components (UI) is stored in AppStorage, including [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md) data. The UI accesses the data through the decorators or APIs provided by AppStorage.
129
130- LocalStorage: an in-memory "database" for the application state declared by the application and typically used to share state across pages. It can be linked to the UI through the [@LocalStorageProp](arkts-localstorage.md#localstorageprop) and [@LocalStorageLink](arkts-localstorage.md#localstoragelink) decorators.
131
132
133### Other Features in State Management V1
134
135[\@Watch](arkts-watch.md): listens for the changes of state variables.
136
137
138[$$operator](arkts-two-way-sync.md): provides a TS variable by-reference to a built-in component so that the variable value and the internal state of that component are kept in sync.
139
140###
141
142
143
144-
145
146-
147
148## State Management (V2)
149
150State management V2 adds new features, such as in-depth observation and property-level update, to state management V1.
151
152### How State Management V2 Stacks Against State Management V1
153
154State management V1 uses a proxy to observe data. When a state variable is created, a data proxy observer is also created. The observer can sense the proxy change but cannot sense the actual data change. Therefore, the observer has the following restrictions:
155
156- State variables cannot exist independently of the UI. When the same data is proxied by multiple views, the change in one view cannot be synchronized to other views.
157- Only the changes at the first layer of object attributes can be sensed, and in-depth observation and listening are not available.
158- Redundant re-renders exist in scenarios where attributes in an object are changed or elements in an array are changed.
159- There are many restrictions on the use of decorators. The input and output of state variables are not specified in components, which is inconvenient for componentization.![arkts-old-state-management](figures/arkts-old-state-management.png)
160
161State management V2 enhances the observation on the data itself. The data itself is observable. This means that changing the data triggers the update of the corresponding view. Compared with state management V1, state management V2 has the following advantages:
162
163- State variables are independent of the UI. Changing data triggers the update of the corresponding view.
164
165- In-depth observation and listening on objects is supported, and the in-depth observation mechanism does not affect the observation performance.
166
167- Objects can be updated at the attribute level, and arrays at the element level.
168
169- The decorators are easier to use and more scalable. The input and output are specified in components, which facilitates componentization.
170
171![arkts-new-state-management](figures/arkts-new-state-management.png)
172
173### Decorator Overview
174
175State management of V2 provides a new set of decorators.
176
177- [\@ObservedV2](arkts-new-observedV2-and-trace.md): \@ObservedV2 allows for in-depth observation on the decorated classes. \@ObservedV2 and \@Trace are used in pairs to enable in-depth observation of properties in a class.
178
179- [\@Trace](arkts-new-observedV2-and-trace.md): \@Trace is used to decorate a property in an \@ObservedV2 class, enabling the property to be observed.
180
181- [\@ComponentV2](arkts-new-componentV2.md): In structs decorated by \@ComponentV2, the following decorators can be used: \@Local, \@Param, \@Event, \@Once, \@Monitor, \@Provider and \@Consumer.
182
183- [\@Local](arkts-new-local.md): An \@Local decorated variable is internal state of the component and cannot be initialized externally.
184
185- [\@Param](arkts-new-param.md): An \@Param decorated variable is used as the input of the component and can be initialized and synchronized externally.
186
187- [\@Once](arkts-new-once.md): An \@Once decorated variable is synchronized only once during initialization and must be used together with \@Param.
188
189- [\@Event](arkts-new-event.md): An \@Event decorated method, as component output, can be used to affect variables in the parent component.
190
191- [\@Monitor](arkts-new-monitor.md): \@Monitor is used in custom components decorated by \@ComponentV2 or classes decorated by \@ObservedV2 to implement in-depth observation on state variables.
192
193- [\@Provider and \@Consumer](arkts-new-Provider-and-Consumer.md): These decorators are used to implement two-way synchronization across component levels.
194
195- [\@Computed](arkts-new-Computed.md): An \@Computed decorated method is a computed property, for which computation is performed only once when the value changes. It is mainly used to solve the performance problem caused by repeated computation when the UI reuses the property multiple times.
196
197- [!! Syntax](arkts-new-binding.md): The **!!** syntax is syntax sugar used for two-way binding.
198
199### Capability Comparison Between State Management V1 and V2
200
201| Decorator of V1  | Decorator of V2                                            | Description                                                        |
202| ------------ | ------------------------------------------------------ | ------------------------------------------------------------ |
203| \@Observed   | \@ObservedV2                                           | Indicates that this object is an observable object. However, each of them have different capabilities.<br>\@Observed is used to observe the top-level properties and it takes effect only when it is used together with \@ObjectLink.<br>\@ObservedV2 does not have the observation capability. It only indicates that this class is observable. To observe the class properties, use together with \@Trace.|
204| \@Track      | \@Trace                                                | \@Track is used for accurate observation. If it is not used, class properties cannot be accurately observed.<br>\@Trace decorated properties can be accurately traced and observed.|
205| \@Component  | \@ComponentV2                                          | \@Component is the custom component decorator used with the state variables of V1.<br>@ComponentV2 is the custom component decorator used with the state variables of V2.|
206| \@State      | No external initialization: @Local<br>External initialization once: \@Param and \@Once| \@State and \@Local decorated variables can work as the data source. The difference is that \@State can be initialized through external input, but \@Local cannot.|
207| \@Prop       | \@Param                                                | Similar to \@Param, \@Prop is used to decorate custom component variables. When the input parameter is of the complex type, \@Prop is used to deep copy and \@Param is used to import the parameter.|
208| \@Link       | \@Param\@Event                                         | \@Link implements a two-way synchronization encapsulated by the framework of V1. Developers using V2 can implement the two-way synchronization through @Param and @Event.|
209| \@ObjectLink            | \@Param                   | Compatible. \@ObjectLink needs to be initialized by the instance of the @Observed decorated class, but \@Param does not have this constraint.|
210| \@Provide    | \@Provider                                             | Compatible.                                                      |
211| \@Consume    | \@Consumer                                             | Compatible.                                                      |
212| \@Watch               | \@Monitor                | \@Watch is used to listen for the changes of state variables and their top-level properties in V1. Observable changes of state variables can trigger the \@Watch listening event.<br>\@Monitor is used to listen for the changes of state variables in V2. Used together with \@Trace, in-depth changes can be listened. When a state variable changes frequently in an event, only the final result is used to determine whether to trigger the \@Monitor listening event.|
213| LocalStorage               | Global \@ObservedV2 and \@Trace  | Compatible.|
214| AppStorage               | AppStorageV2   | Compatible.|
215| Environment       | Calls the ability APIs to obtain system environment variables.  | This capability is coupled with the AppStorage. In V2, you can directly call the ability APIs to obtain system environment variables.|
216| PersistentStorage     | PersistenceV2   | The persistence capability of PersistentStorage is coupled with the AppStorage, while that of PersistenceV2 can be used independently.|
217
218For details about how to migrate applications from V1 to V2, see [Migrating Applications from V1 to V2](./arkts-v1-v2-migration.md).<br>For details about how to use decorators of V1 and V2 together, see [Mixing Use of Custom Components](./arkts-custom-component-mixed-scenarios.md).
219