Lifecycle Hooks — Complete Guide
Lifecycle Hooks — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 16 of 100
Lifecycle Hooks
Stack → Projects
Stack · 1 — Pieces · ~6 min · MEAN — Fundamentals
What is this?
Lifecycle hooks are methods Angular calls at specific times — ngOnInit after inputs set, ngOnDestroy before teardown.
Why should you care?
MeanVerse components subscribing to sockets or intervals must clean up in ngOnDestroy to prevent memory leaks.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
@Component({ standalone: true, template: `<p>Live rate: {{ rate }}</p>` })
export class FxRateComponent implements OnInit, OnDestroy {
rate = 0;
private sub?: Subscription;
ngOnInit(): void {
this.sub = this.fx.stream('USD/EUR').subscribe(r => (this.rate = r));
}
ngOnDestroy(): void {
this.sub?.unsubscribe();
}
}
What happened?
- ngOnInit runs once after first change detection — good for subscriptions.
- ngOnDestroy unsubscribes so the socket does not keep updating a destroyed view.
Practice next
- build OnInit to load data when route param changes.
- Store Subscription and unsubscribe in ngOnDestroy.
- Prefer takeUntilDestroyed() in Angular 16+ as alternative.
- Refactor to signal + toObservable with automatic cleanup.
- Log hook order in a demo component to see sequence.
Remember
ngOnInit = setup; ngOnDestroy = cleanup. Unsubscribe or use async pipe / takeUntilDestroyed. Hooks map to component birth and death.
Trading desk ticker
MeanVerse FX widget streams rates; user navigates away mid-session.
Outcome: ngOnDestroy stops updates — no ghost network traffic.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!