Course Progress 83%

Angular State Management

Angular State Management का मतलब है application के data और UI state को predictable, maintainable और scalable तरीके से manage करना। जैसे-जैसे application बड़ा होता है, components के बीच data sharing, synchronization और consistency बड़ी challenge बन जाती है। State Management इन problems को systematically solve करता है।

इस chapter में हम Angular में state management को basic concepts से लेकर modern Angular patterns तक deep में समझेंगे, बिना किसी external library पर immediately depend किए।

State क्या होता है

State उस data को कहते हैं जो application के current condition को represent करता है।

Examples:

  • Logged-in user information
  • Cart items
  • Form data
  • UI flags (loading, error, success)

State change होने पर UI भी update होता है।

Angular में State की Types

Angular applications में broadly तीन types की state होती हैं:

  • Local State (component-level)
  • Shared State (multiple components)
  • Global State (application-wide)

हर state type के लिए approach अलग होती है।

Local State Management

Local state component के अंदर manage होती है।

export class ProfileComponent {
  isEditing = false;
}

यह simple cases के लिए best है, लेकिन sharing के लिए suitable नहीं।

Shared State Using Services

Angular services shared state के लिए default solution हैं।

@Injectable({ providedIn: 'root' })
export class CounterService {
  count = 0;

  increment() {
    this.count++;
  }
}

Multiple components same service instance share करते हैं।

यह lightweight state management है।

Problems with Simple Service State

Simple service state के limitations:

  • Change tracking difficult
  • State mutations unpredictable
  • Side effects control नहीं होते
  • Debugging मुश्किल

Large apps में structured approach जरूरी होती है।

Reactive State with RxJS

RxJS Angular state management का strong foundation है।

private state$ = new BehaviorSubject<number>(0);

getState() {
  return this.state$.asObservable();
}

setState(value: number) {
  this.state$.next(value);
}

Benefits:

  • Predictable updates
  • Multiple subscribers
  • Async-friendly

Components:

this.service.getState().subscribe(v => this.value = v);

Immutable State Concept

Advanced state management immutable state follow करता है।

updateUser(user: User) {
  this.state$.next({ ...this.state$.value, user });
}

Benefits:

  • Easier debugging
  • Change detection reliable
  • Side effects reduced

Immutable updates professional Angular apps में standard हैं।

State as Single Source of Truth

Application state centralized होनी चाहिए।

Rules:

  • State change एक place से हो
  • Components directly state mutate न करें
  • State observable हो

यह consistency maintain करता है।

UI State Management

UI-related state भी important होती है।

Examples:

  • loading
  • error
  • success
interface UiState {
  loading: boolean;
  error: string | null;
}

UI और data state separate रखना best practice है।

State + HTTP Integration

API calls के साथ state manage करना common requirement है।

loadUsers() {
  this.state$.next({ ...this.state$.value, loading: true });

  this.http.get('/users').subscribe(data => {
    this.state$.next({ data, loading: false });
  });
}

Service API + state orchestration handle करती है।

Derived State (Selectors Concept)

Derived state original state से compute होती है।

get activeUsers$() {
  return this.state$.pipe(
    map(state => state.users.filter(u => u.active))
  );
}

यह duplication avoid करता है।

Angular Signals for State Management

Modern Angular में Signals state management simplify करते हैं।

@Injectable({ providedIn: 'root' })
export class CounterState {
  count = signal(0);

  increment() {
    this.count.update(v => v + 1);
  }
}

Components reactive तरीके से state consume करते हैं।

Computed Signals (Derived State)

total = computed(() => this.count() * 2);

यह RxJS selectors का modern alternative है।

Signals vs RxJS State

RxJS:

  • Powerful async flows
  • Complex pipelines

Signals:

  • Simple synchronous state
  • Fine-grained reactivity

Modern Angular apps में hybrid approach common है।

State Encapsulation

State directly expose न करें।

private state = signal<AppState>(initialState);

readonly vm = computed(() => this.state());

यह accidental mutation prevent करता है।

Feature-Level State

State feature-wise split करना scalable approach है।

  • AuthState
  • ProductState
  • CartState

हर feature की clear responsibility होती है।

Lazy-Loaded State Considerations

Lazy modules के साथ state duplication risk होता है।

Solutions:

  • Root-level state services
  • providedIn: ‘root’
  • Avoid providedIn: ‘any’ for global state

State Reset Strategies

Logout या navigation पर state reset करना जरूरी होता है।

reset() {
  this.state.set(initialState);
}

State lifecycle control professional apps में critical है।

Error Handling in State

Errors भी state का हिस्सा होनी चाहिए।

catchError(err => {
  this.state.update(s => ({ ...s, error: err }));
  return EMPTY;
});

UI error handling predictable बनती है।

Testing State Management

State logic easily testable होती है।

service.increment();
expect(service.count()).toBe(1);

Predictable state = reliable tests।

Common State Management Mistakes

  • Global state overuse
  • Direct mutation
  • Business logic component में रखना
  • UI और data state mix करना

When to Introduce External Libraries

External libraries जैसे NgRx तब introduce करें जब:

  • App बहुत large हो
  • Complex async flows हों
  • Strict predictability चाहिए हो

Small to medium apps के लिए Angular native tools sufficient होते हैं।

Angular State Management Angular applications की long-term health decide करता है। Services, RxJS और Signals का सही balance रखकर आप scalable और maintainable Angular apps build कर सकते हैं। अगले chapter में हम Signals vs RxJS को deep comparison के साथ cover करेंगे।