Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 20

Managing State: Collections and Variables

Recommended resources

Hello! Let's continue our journey into building professional Canvas Apps.

In our last lesson, we focused on performing CRUD operations on data that is permanently stored in a data source like Dataverse or SharePoint. Today, we shift our focus from persistent data to temporary data—information that lives in your app's memory only while it's running.

This lesson addresses the learning outcome: Manage app state and temporary data using collections and variables. Mastering this is crucial for building responsive, performant, and sophisticated user interfaces. We'll explore how to temporarily store single values (variables) and tables of data (collections) to manage UI state, cache data for performance, and stage complex data before saving it.

Given your background in C# and JavaScript, you'll find these concepts familiar. Think of Power Fx variables as being similar to variables in any programming language, with different scopes (global vs. local). Collections are the Power Fx equivalent of an in-memory list or array of objects, like a List<T> in C# or an array of objects in JavaScript.

Understanding Variables in Power Apps

Variables are containers for storing information. In Power Apps, we primarily work with two types: global variables and context variables. The key difference between them is their scope.

To get a practical, hands-on introduction, we'll start with a video that clearly explains the differences, syntax, and common use cases for each.

Power Apps Variables: Global vs. Context and what you need to know

This video from Shane Young provides an excellent, practical overview of global and context variables. It covers how to create them, their scope, and common pitfalls.

Please watch the following segments: Global Variables with Set (01:35 - 06:36): Observe how the Set function creates a variable that is accessible on any screen in the app. Note the different data types that can be stored, including records. Context Variables with UpdateContext (06:36 - 09:36): Pay close attention to how UpdateContext creates a variable that is only available on the screen where it was defined. This screen-specific scope is the most important distinction. Self-Referencing and Toggling (12:23 - 16:02): This section demonstrates powerful patterns like toggling a boolean value (!variable) and creating counters (variable + 1), which are extremely common for managing UI state.

Global Variables (Set)

As you saw in the video, global variables are created using the Set function and are available throughout your entire app.

  • Syntax: Set(VariableName, Value)
  • Scope: App-wide. Accessible from any screen.
  • Common Uses:
    • Storing user information after login (e.g., Set(gblCurrentUser, User())).
    • App-wide settings, like a theme or user preferences.
    • Storing a record retrieved from a data source that needs to be referenced on multiple screens.

While powerful, overusing global variables can make your app difficult to debug and can negatively impact performance by cluttering memory. A good rule of thumb is to ask: "Does this data truly need to be accessible everywhere?" If not, a context variable is likely a better choice.

Context Variables (UpdateContext)

Context variables are scoped to a single screen, making them ideal for managing temporary state within that screen.

  • Syntax: UpdateContext({VariableName: Value, VariableName2: Value2})
    • Note the curly braces {}. UpdateContext accepts a record, allowing you to set or update multiple context variables on that screen at once.
  • Scope: Local to the screen where they are defined. They are automatically cleared when the user navigates away from the screen.
Power Apps Variable Scope: Local Variable Limitation
This image clearly illustrates that a context variable (referred to as a 'local variable' here) defined on one screen is not accessible from another, demonstrating its screen-specific scope.
  • Common Uses:
    • Toggling the visibility of a popup, panel, or loading spinner (UpdateContext({showPopup: true})).
    • Storing temporary user input on a form before it's processed.
    • Managing the state of controls on a specific screen.

You can also pass data to a destination screen during navigation, which creates context variables on that screen. This is the preferred method for passing data between screens, as it avoids creating unnecessary global variables.

// On Screen1, navigate to Screen2 and pass a record ID as a context variable
Navigate(Screen2, ScreenTransition.None, {selectedRecordId: 123})

// On Screen2, 'selectedRecordId' is now available as a context variable.

Managing Tabular Data with Collections

While variables are great for single values (text, numbers, booleans, records), collections are used to store tables of data in memory. They are essential for caching data to improve performance and for staging data before writing it to a data source.

Power Apps Studio Variables Pane Highlighting Collections
Collections you create are visible in the 'Variables' pane in Power Apps Studio, where they are listed as tables with a row count.

The core functions for managing collections are:

  • Collect(CollectionName, Item): Adds a record to a collection. If the collection doesn't exist, it is created.
  • Clear(CollectionName): Removes all records from a collection, leaving it empty.
  • ClearCollect(CollectionName, Items): Clears all existing records and then adds a new set of records. This is very common for refreshing a local cache of data.

Let's watch a video that demonstrates these functions and their most important use cases.

Power Apps Collections Introduction

This video, also from Shane Young, is a fantastic introduction to collections. It covers the essential functions and demonstrates the two most critical use cases: staging data and caching data from a source.

Please watch these key segments: Creating a Collection with Collect (01:25 - 04:24): Understand the basic syntax for creating a collection and adding records. Clear and ClearCollect (04:24 - 06:26): Grasp the difference between adding to a collection (Collect), emptying it (Clear), and replacing its contents (ClearCollect). Collecting from User Inputs (06:26 - 09:46): See how to dynamically add data from input controls into a collection. Caching Data from a Data Source (09:46 - 14:40): This is a critical performance pattern. Pay attention to how ClearCollect is used to pull an entire SharePoint list into a local collection to speed up lookups. Note the important mention of delegation limits.

Key Use Cases for Collections

  1. Staging Data (Shopping Cart Pattern):
    Imagine an expense report app where a user adds multiple line items before submitting the whole report. Each line item can be added to a colExpenseItems collection. When the user clicks "Submit," you can then use the ForAll and Patch functions to write every record from the collection to your data source at once. We'll cover this bulk update pattern in our next lesson.

    // On 'Add Item' button click
    Collect(
        colExpenseItems,
        {
            ItemName: txtItemName.Text,
            Cost: Value(txtCost.Text),
            Date: dpDate.SelectedDate
        }
    )
    
  2. Caching Data for Performance:
    If you have a small-to-medium sized list of data that doesn't change often (e.g., a list of departments, categories, or statuses), it's much more efficient to load it into a collection once when the app starts.

    App.OnStart property:

    // Load all records from the 'Departments' table into a collection
    ClearCollect(colDepartments, Departments)
    

    Now, any time you need to look up a department name in your app, you can reference the colDepartments collection instead of making a new call to the data source. This makes your app feel much faster, as in-memory operations are nearly instantaneous compared to network requests.

    Warning: ClearCollect is not delegable. This means it can only retrieve up to the data row limit for non-delegable queries (default is 500, max is 2,000). This pattern is not suitable for large data sources.


A Modern Alternative: Named Formulas

Recently, Microsoft introduced Named Formulas, a powerful alternative to using global variables for values that should not change during the app session. They are defined once in the App.Formulas property and behave like declarative constants or expressions that automatically recalculate if their dependencies change.

From a developer's perspective, they offer several advantages over setting global variables in App.OnStart.

App object in Power Apps - Formulas property

The official Microsoft documentation provides the most precise definition of Named Formulas and their benefits. This will appeal to your developer background.

Read the section titled 'Formulas property'. Focus on the list of advantages provided. Understanding these will help you decide when to use a Named Formula instead of a global variable.

Key advantages include:

  • Always available: No timing dependency on App.OnStart to run first.
  • Always up-to-date: Automatically recalculates when dependencies change.
  • Immutable: The definition is the single source of truth and cannot be changed by other code, preventing bugs.
  • Improved App Load Time: Their calculation can be deferred until the value is actually needed, which can speed up your app's initial load.

Example: Instead of Set(gblUserEmail, User().Email) in App.OnStart, you define this in App.Formulas:
UserEmail = User().Email;

Now, UserEmail is available throughout the app just like a global variable, but with the added benefits of being declarative and optimized.

Test your understanding!

You are building a simple product ordering screen. You have a gallery of products (galProducts) from a 'Products' data source.

  1. You want to show a popup with more details when a user selects a product. Write the formula for an icon inside the gallery to set a context variable named ctxShowPopup to true.
  2. On the "Add to Order" button inside the popup, you need to add the selected product to a collection named colOrderItems. The product record can be identified by galProducts.Selected. Write the formula for this button.
  3. You have a label that should display the total number of items in the order. What formula would you use for the Text property of this label, using the colOrderItems collection?
  4. Finally, you need a "Clear Order" button. Write the formula to empty the colOrderItems collection.
Show answer
  1. Show Popup Formula:

    UpdateContext({ctxShowPopup: true})
    

    You would then set the Visible property of your popup container to ctxShowPopup.

  2. Add to Order Formula:

    Collect(colOrderItems, galProducts.Selected)
    

    This adds the entire record of the selected product to the colOrderItems collection.

  3. Order Count Formula:

    "Items in order: " & CountRows(colOrderItems)
    

    The CountRows function returns the number of records in a table or collection.

  4. Clear Order Formula:

    Clear(colOrderItems)
    

Conclusion

You have now learned the essential techniques for managing temporary data and state within your Canvas Apps. This is a fundamental skill that separates simple apps from sophisticated, high-performance applications.

Key Takeaways:

  • Use context variables (UpdateContext) for temporary, screen-specific state like UI visibility.
  • Use global variables (Set) sparingly for truly app-wide information like user settings.
  • Use collections (Collect, ClearCollect, Clear) to manage in-memory tables of data, perfect for caching and staging.
  • Consider Named Formulas as a modern, declarative, and performant alternative to global variables for static or derived values.

Up Next:
Now that you know how to build a collection of records (like the "shopping cart" or "order items" examples), the next logical step is to save that entire collection to your data source. In our next lesson, "Implement bulk data operations by combining the ForAll and Patch functions," we will do exactly that, exploring one of the most powerful and efficient data-writing patterns in Power Apps.