Back to results for “Dependency Injection”
Angular › Lifecycle Hooks

What are lifecycle hooks in Angular and why would you use them?

Beginner

Answer

Lifecycle hooks are special methods Angular calls automatically at specific points in a component's life, such as right after it is created or right before it is destroyed, letting you run your own code exactly when needed, like fetching data or cleaning up a resource.
import { OnInit } from '@angular/core';

@Component({ selector: 'app-profile' })
export class ProfileComponent implements OnInit {
  ngOnInit() {
    console.log('Component has been initialized');
  }
}
Real-world example A profile component fetches the user's data as soon as it is created, using the ngOnInit lifecycle hook to trigger that initial data load exactly once.

Common follow-ups: Why is ngOnInit generally preferred over the constructor for fetching data?;What other common lifecycle hooks does Angular provide besides ngOnInit?