State Management Made Easy with Akita in Angular

author

Mariselvan M

August 25, 2023

Last updated: November 15, 2023

Akita State Management

State management is one of the most important aspects of web development, as it determines how data flows and changes in an application. It can affect the performance, scalability, and maintainability of your web app. But what exactly is state management and why do you need it?

In this blog, we will explore the concept of state management, the common types & how it helps with web application development. We will also explore centralized state management and how Akita state management helps us to facilitate the data flow in the application by managing it.

Whether you are using React, Angular 16, Vue.js, or any other framework, you will find some useful insights and tips on how to manage your application’s state effectively.

What is state management?

State management is the process of managing one or more states of user controls in a graphical user interface. It helps the development team to build large-scale applications with heavy data communications without any compromises on the high application performance.

CommonTypes of State Management:

Local State Management

In local state management, components handle their own data and state changes independently, making it ideal to be used with simple components without sharing data among others.

Centralized State Management

Centralized state management uses a single store for the application’s state, allowing components to access and modify shared data through specific patterns. It ensures consistent state synchronization and is implemented by libraries like Redux (for React), NgRx (for Angular), and Vuex (for Vue.js).

Distributed State Management

Distributed state management handles states across multiple nodes or instances in a distributed system to ensure high availability and scalability. Techniques like event sourcing and CQRS are used in such scenarios.

When it comes to Angular, Akita, NgRx, and Elf are the three most-used libraries for centralized state management, and they have some unique features that make developers’ work easy.

Now that we have a clear idea about the common types of state management, let us look at the goals of state management.

The main goals of state management are

Consistency:

State management ensures that the application’s data remains consistent and up-to-date across different components and modules.

Predictability:

By following specific patterns or techniques, state management ensures that state changes are predictable and can be easily traced or debugged.

Reactivity:

State management enables the application to react to changes in data and update the user interface accordingly.

Data Sharing:

It allows data to be shared and accessed between different parts of the application.

Scalability:

Proper state management is crucial as it will facilitate the handling of complex data and interactions as the application gets scaled in the future.

Why State Management is Important?

Web apps are getting richer and more complex. Managing the state is exponentially harder than it used to be. Different parts of an application have various responsibilities, and those (components, directives, etc.) are segregated across many different files, however, they all need to reflect the same underlying state.

A state management library will be helpful to get the following things done:

  • Model your application state
  • Derive computed values from it
  • Monitor it for changes

It gives us many benefits like handling normalized data (redundant models can be avoided), immutability and organized state transition, time travel ability, and more.

Now that we have seen the importance of state management, we will try to understand the application state in the context of an Angular application.

Angular applications are typically made up of many components and each of these components has its own state. They will have no awareness of the state of the other components. To share information between parent-child components in it, we use @Input and @Output decorators.

However, this approach is possible only if the application consists of a few components, as shown in the flowchart below.

When the number of components grows, it becomes a cumbersome task to transfer the information between components solely via @Input and @Output decorators.

Let’s take the following flowchart to elaborate on this.

If you pass information from component three to component six, you must hop four times and involve three other components. It is evident that managing the state can be very complex. Having a state management solution such as Akita can come in handy in a situation like this. It will simply transform the above data transfer model into something similar to the one below.

As this architecture suggests, data flows between the store and components, instead of moving from component to component.

Introduction to Akita

Akita is a state management pattern, built on RxJS and is based on object-oriented design principles.

Akita state management encourages simplicity and also saves the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve. It will be suitable for both experienced and inexperienced developers.

State Management for Angular Akita Architecture

Key features and concepts of Akita:

Model:

The general representation of the data model that the store is going to manage.

Stores:

In Akita, the central building block is the store, which holds the application’s state. Each store corresponds to a specific data entity or domain within the application. You can execute all the DML (Data Manipulation Language) with the help of Akita built-in store methods like add(), update(), delete(), setActive(), setError(), etc.

There are two types of stores:

The Basic Store:

When our model doesn’t represent a collection of entities, e.g., session, UI states, etc.

The Entity Store:

When we need to maintain a collection of entities e.g., domain model – employee, student, etc.

Entities:

Akita uses entities to manage data. Entities are objects that represent individual records in the state. Each entity has a unique ID, allowing for easy retrieval and manipulation of data.

Queries:

  • Akita provides query APIs to efficiently access and filter data from the stores. Queries allow developers to retrieve and compose data from the store without directly accessing the state.
  • The query results are available in two forms — reactive queries and synchronized queries.
  • You can run all the DDL (Data Definition Language) with the help of Akita built-in query methods like select(), selectAll(), selectEntity(), selectCount(), selectActive(), etc.

Actions:

Actions in Akita are plain JavaScript objects that represent events or operations that can modify the state. Actions are dispatched to the store to trigger state updates.

Updaters:

Updaters are functions responsible for updating the state based on the dispatched actions. These updaters define how the state should change in response to different actions made on the components.

Akita Service:

Akita provides a service layer that allows developers to interact with the store and perform CRUD (Create, Read, Update, Delete) operations easily.

Plugins:

Akita supports plugins that extend its functionality. Plugins provide additional features like persistence, entity caching, and more.

By using these building blocks, developers can efficiently manage the state of their Angular applications. Akita’s well-structured and pragmatic design allows for a straightforward approach to state management in Angular, making it easier to maintain and scale applications as they grow in complexity.

A Simple Example of how Akita works with an Angular application:

1. Install Akita

First, install Akita and its dependencies in your Angular project using npm or yarn

npm install @datorama/akita 

Next, create a store using Akita. Let’s say we want to manage a list of products. Create a new file called product.store.ts and define the store as follows –

Screengrab of creating a new file called product.store.ts

In the ‘ProductStore‘, we extend the 'EntityStore' class provided by Akita. It automatically provides methods for managing entities of type ‘Product‘. We also specify the store name as 'products' using the ‘StoreConfig‘ decorator.

3. Define a Model

Create a product.model.ts file to define the Product model

Screengrab of defining the Product model

4. Access and Update State

In your component or service, you can access the ‘ProductStore‘ and interact with the state. For example, let’s say we have a ‘ProductListComponent

Screengrab of accessing the product store

In the ProductListComponent, we inject the ProductStore and subscribe to the selectAll() method, which returns an observable of all products in the store. We can then use the products$ observable in the template to display the list of products.

5. Updating State

To update the state, you can use the provided methods in the ProductStore, such as add(), update(), or remove(). For example, let’s say we have a ProductService that handles API requests and updates the store –

Screengrab of ProductService handling API requests and updates the store

In the ProductService, we inject the ProductStore and use the provided methods to add, update, or remove products from the store.
By following this pattern, you can manage and update the state of the products store using Akita’s centralized state management in Angular application.

Here are some common advantages and disadvantages of state management:

Advantages of using Akita

Simplicity

Akita is designed to have a straightforward API, making it easy for developers to adopt and use in their applications.

Performance

Akita’s query system and data caching mechanism contribute to better performance and efficient state retrieval.

Developer Experience

Akita’s well-organized structure and tooling enhance the developer experience, ease the debugging process and maintenance.

Scalability

With its pragmatic approach, Akita is well-suited for projects of different scales, from simple applications to complex systems.

Integration

Akita can be seamlessly integrated with Angular applications, providing a familiar and consistent development experience.

Disadvantages of using Akita:

Learning Curve

If developers are new to Akita or state management concepts in general, there might be a learning curve to understand its principles, API, and best practices.

Additional Dependency

Adding Akita to an Angular project introduces an additional dependency, increasing the bundle size and potentially affecting the application’s initial load time.

Redux-like Pattern

Akita follows a Redux-like pattern, which involves setting up stores, actions, and updaters. Some developers might find this pattern too verbose or complex for smaller applications.

Initial Setup

While Akita provides some boilerplate reduction, setting up stores and defining actions and updates might require more upfront configuration compared to other simpler state management solutions.

Migration from Other Libraries

If developers are already using a different state management library in their Angular project, migrating to Akita might require additional effort and time.

Plugin Compatibility

Although Akita supports plugins, some might be less maintained or less compatible with the latest versions of Akita or Angular, leading to potential issues or limitations.

Customization Complexity

While Akita provides some built-in functionalities, complex customization or unique state management requirements might require more effort or workarounds.

Abstraction Overhead

Depending on the application’s scale and complexity, introducing state management might add some abstraction overhead, leading to less direct control over data manipulation.

Small Community

While Akita has a growing community, it might not be as extensive as other more established state management libraries like NgRx, leading to potentially fewer online resources and examples.

Limited Features

Compared to other more feature-rich state management libraries, Akita might have fewer built-in features and might require developers to implement some functionalities manually.

Akita is a robust state management library for Angular applications, but like any tool, it has its trade-offs.

It’s important to note that the pros and cons of state management can vary depending on the specific implementation, the requirements of the application, and the expertise of the development team. It is crucial to carefully evaluate these factors before deciding on the appropriate state management approach for a given project.

Conclusion

State management is a complex aspect and a crucial skill for web developers as the benefits of Angular web application development are endless. Choosing the right tools and patterns can significantly enhance their productivity and help them deliver stunning user experiences.
In short, Akita will help to manage all your data in one place and give you a strong abstraction on handling both DML or DDL operations that we perform on the data.

Related Articles

field image

Stuck in the Insurance Stone Age? Discover the Power of Portal Software in 2024 Remember those rolodexes and fax machines? Yeah, the insurance industry can feel a bit like that sometimes. But what if you could ditch the outdated tools and access a war room of information – all online and at your fingertips? Here’s […]

author-image

Calibraint

Author

26 Apr 2024

field image

Forget “For Sale” signs outside houses and endless cold calls. The future of real estate lead generation is undeniably digital. In today’s world, potential buyers begin their home search online, making a wide web presence crucial for any agent looking to maximize property sales.  In this blog post, we will explore how these innovative tools […]

author-image

Calibraint

Author

04 Apr 2024

field image

An Introduction To Cost Reduction In Inventory Management Do you ever feel like you’re constantly playing inventory whack-a-mole? Stockouts costing you sales? Or maybe you’re drowning in a sea of unused products eating away at your profits? Inefficient inventory management can be a major drain on your business resources. But what if there was a […]

author-image

Haritha

29 Mar 2024

field image

What If I Told You That A Website Is Already An App? There is a saying “If you can’t convince them, confuse them”! This is exactly what Web Apps and Mobile Apps do with us. So if “Web App vs Mobile App: Which one should I choose” is your question, then this blog has all […]

author-image

Calibraint

Author

13 Feb 2024

field image

PWAs are no longer a futuristic fantasy; they’re a present-day reality, transforming how businesses connect with their audience. Stats back this up as several reports suggest increased conversions and user engagement with PWAs over traditional websites. And let’s not forget the search engine love – PWAs get indexed and appear in app store listings, expanding […]

author-image

Calibraint

Author

10 Feb 2024

field image

WE HAVE DETECTED AN UNSAFE LINK!!!! Ever felt that gut-wrenching ‘ohhh noo’ moment when you realize your website is under attack? In 2024, the web is a wild west of cyber threats, and your website might be the next frontier.  Picture this: Everything you’ve built vanished in the blink of a malicious code. But fear […]

author-image

Haritha

25 Jan 2024

Let's Start A Conversation

Table of Contents