Gourav Pokharkar
Gourav Pokharkar

Reputation: 1648

What does a state mean in Angular application?

I am new to NgRx and going through its documentation. But, at the beginning, I'm encountered with the following sentence:

State is a single, immutable data structure.

What does the state mean in simple words? Need some simple examples to understand this concept.

Do I need to learn Flux and Redux to understand these concepts?

Upvotes: 1

Views: 1335

Answers (1)

yuval.bl
yuval.bl

Reputation: 5074

Simply put, a state in ngrx (or redux, or other state managment systems) is how your system is described in a single point in time.

You can think about it as a plain javascript object that represent your entire application at one point. Let's take a simple example of a todos app, where i can mark a completed item (by a completed flag) or selected item (by index). a possible state might look like this:

{
  items: [
    { text: 'Wash Car', completed: false},
    { text: 'Write Code', completed: true}
  ],
  selectedIndex: 0
}

If I'll decide to select the second index, my state future state would look like this:

{
  items: [
    { text: 'Wash Car', completed: false},
    { text: 'Write Code', completed: true}
  ],
  selectedIndex: 1
}

So, a state is a representation of your app logic in a single point of time. The view implementation is up to you - angular, react, and mobile application can share the same state and use different view layer.

Some state-management system require the state to be immutable, meaning that in the todos example I wouldn't simply change my state, but rather create an entire new state to represent the change in the system.

There are multiple reasons for that, but maybe the most obvious one is that this quality help web systems to recognize changes in the state, and change the view accordingly.

NgRx is an angular-specific state management system. as described in NgRx page:

NgRx Store provides reactive state management for Angular apps inspired by Redux.

So, a good point to state would be to learn redux (The rule of immutability comes from redux). You can look at NgRx as a redux-based state management, power with RxJS. I would suggest to learn each concept desperately and then move to learn NgRx.

Update: These questions might be useful

  1. Why should objects in Redux be immutable?
  2. Redux: why using Object.assign if it is not perform deep clone?

Upvotes: 3

Related Questions